diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..725ca5195 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,13 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 1.5.x | :white_check_mark: | +| 1.4.x | :white_check_mark: | +| < 1.4.0 | :x: | + +## Reporting a Vulnerability + +Please report (suspected) security vulnerabilities to support@qloapps.com. You will receive a response from us within 48 hours. If the issue is confirmed, we will release a patch as soon as possible depending on complexity. diff --git a/admin/ajax.php b/admin/ajax.php index be2c91bc4..2506e809d 100644 --- a/admin/ajax.php +++ b/admin/ajax.php @@ -72,12 +72,12 @@ if (Tools::isSubmit('ajaxProductPackItems')) { if (Tools::isSubmit('getChildrenCategories') && Tools::isSubmit('id_category_parent')) { $children_categories = Category::getChildrenWithNbSelectedSubCat(Tools::getValue('id_category_parent'), Tools::getValue('selectedCat'), Context::getContext()->language->id, null, Tools::getValue('use_shop_context')); - die(Tools::jsonEncode($children_categories)); + die(json_encode($children_categories)); } if (Tools::isSubmit('getNotifications')) { $notification = new Notification; - die(Tools::jsonEncode($notification->getLastElements())); + die(json_encode($notification->getLastElements())); } if (Tools::isSubmit('updateElementEmployee') && Tools::getValue('updateElementEmployeeType')) { @@ -111,7 +111,7 @@ if (Tools::isSubmit('getParentCategoriesId') && $id_category = Tools::getValue(' $output[] = $result; } - die(Tools::jsonEncode($output)); + die(json_encode($output)); } if (Tools::isSubmit('getZones')) { @@ -121,7 +121,7 @@ if (Tools::isSubmit('getZones')) { } $html .= ''; $array = array('hasError' => false, 'errors' => '', 'data' => $html); - die(Tools::jsonEncode($array)); + die(json_encode($array)); } if (Tools::isSubmit('getEmailHTML') && $email = Tools::getValue('email')) { diff --git a/admin/ajax_products_list.php b/admin/ajax_products_list.php index 137020a37..03a5f4999 100644 --- a/admin/ajax_products_list.php +++ b/admin/ajax_products_list.php @@ -137,7 +137,7 @@ if ($items && ($excludeIds || strpos($_SERVER['HTTP_REFERER'], 'AdminScenes') != } } $results = array_values($results); - echo Tools::jsonEncode($results); + echo json_encode($results); } else { - Tools::jsonEncode(new stdClass); + json_encode(new stdClass); } diff --git a/admin/functions.php b/admin/functions.php index 15c397049..ae72f6340 100644 --- a/admin/functions.php +++ b/admin/functions.php @@ -524,8 +524,8 @@ function runAdminTab($tab, $ajax_mode = false) } // we can display the correct url - // die(Tools::jsonEncode(array(Translate::getAdminTranslation('Invalid security token'),$url))); - die(Tools::jsonEncode(Translate::getAdminTranslation('Invalid security token'))); + // die(json_encode(array(Translate::getAdminTranslation('Invalid security token'),$url))); + die(json_encode(Translate::getAdminTranslation('Invalid security token'))); } else { // If this is an XSS attempt, then we should only display a simple, secure page if (ob_get_level() && ob_get_length() > 0) { diff --git a/admin/themes/default/template/controllers/orders/helpers/view/view.tpl b/admin/themes/default/template/controllers/orders/helpers/view/view.tpl index 5421912fe..d300dc815 100644 --- a/admin/themes/default/template/controllers/orders/helpers/view/view.tpl +++ b/admin/themes/default/template/controllers/orders/helpers/view/view.tpl @@ -301,11 +301,11 @@
- {if $data['id_status'] == 2}{l s='checked in on'} {$data['check_in']|date_format:"%d-%m-%Y"}{elseif $data['id_status'] == 3}{l s='checked out on'} {$data['check_out']|date_format:"%d-%m-%Y"}{/if} + {if $data['id_status'] == $hotel_order_status['STATUS_CHECKED_IN']['id_status']}{l s='checked in on'} {$data['check_in']|date_format:"%d-%m-%Y"}{elseif $data['id_status'] == $hotel_order_status['STATUS_CHECKED_OUT']['id_status']}{l s='checked out on'} {$data['check_out']|date_format:"%d-%m-%Y"}{/if} {* field for the current date *} diff --git a/classes/Blowfish.php b/classes/Blowfish.php index d052820c2..a4aeba50a 100644 --- a/classes/Blowfish.php +++ b/classes/Blowfish.php @@ -377,7 +377,7 @@ class Crypt_Blowfish for ($i = 0; $i < 18; $i++) { $data = 0; for ($j = 4; $j > 0; $j--) { - $data = $data << 8 | ord($key{$k}); + $data = $data << 8 | ord($key[$k]); $k = ($k + 1) % $len; } $this->_P[$i] ^= $data; diff --git a/classes/Cart.php b/classes/Cart.php index 7d380889b..bceb9ac72 100644 --- a/classes/Cart.php +++ b/classes/Cart.php @@ -2632,6 +2632,9 @@ class CartCore extends ObjectModel */ public static function desintifier($int, $delimiter = ',') { + if (!$int) + return; + $delimiter_len = $int[0]; $int = strrev(substr($int, 1)); $elm = explode(str_repeat('0', $delimiter_len + 1), $int); @@ -4317,7 +4320,7 @@ class CartCore extends ObjectModel $postData = trim(file_get_contents('php://input')); libxml_use_internal_errors(true); $xml = simplexml_load_string(utf8_decode($postData)); - $cartData = Tools::jsonDecode(Tools::jsonEncode($xml, true)); + $cartData = json_decode(json_encode($xml, true)); $this->id_address_delivery = $cartData->cart->id_address; $this->id_address_invoice = $cartData->cart->id_address; @@ -4344,7 +4347,7 @@ class CartCore extends ObjectModel $postData = trim(file_get_contents('php://input')); libxml_use_internal_errors(true); $xml = simplexml_load_string(utf8_decode($postData)); - $cartData = Tools::jsonDecode(Tools::jsonEncode($xml, true)); + $cartData = json_decode(json_encode($xml, true)); $this->id_address_delivery = $cartData->cart->id_address; $this->id_address_invoice = $cartData->cart->id_address; @@ -4384,14 +4387,14 @@ class CartCore extends ObjectModel $extraDemands = null; foreach ($bookingRows as $booking) { - $booking = Tools::jsonDecode(Tools::jsonEncode($booking, true), true); + $booking = json_decode(json_encode($booking, true), true); if (isset($booking['extra_demands']['extra_demand'])) { $extraDemands = $booking['extra_demands']['extra_demand']; if (isset($extraDemands['id_global_demand'])) { $extraDemands = array($extraDemands); } - // $extraDemands = Tools::jsonDecode($extraDemands, true); - $extraDemands = Tools::jsonEncode($extraDemands); + // $extraDemands = json_decode($extraDemands, true); + $extraDemands = json_encode($extraDemands); } // get room booking info diff --git a/classes/CartRule.php b/classes/CartRule.php index d93f70b8b..88670b0de 100644 --- a/classes/CartRule.php +++ b/classes/CartRule.php @@ -1220,7 +1220,7 @@ class CartRuleCore extends ObjectModel if ($type == 'shop') { $shops = Context::getContext()->employee->getAssociatedShops(); if (count($shops)) { - $shop_list = ' AND t.id_shop IN ('.implode(array_map('intval', $shops), ',').') '; + $shop_list = ' AND t.id_shop IN ('.implode(',', array_map('intval', $shops)).') '; } } diff --git a/classes/ConfigurationTest.php b/classes/ConfigurationTest.php index 0ada14877..fa5ff10e3 100644 --- a/classes/ConfigurationTest.php +++ b/classes/ConfigurationTest.php @@ -31,7 +31,7 @@ class ConfigurationTestCore '/classes/log/index.php', '/classes/cache/index.php', '/config/index.php', - '/tools/tar/Archive_Tar.php', + '/tools/tar/Tar.php', '/tools/pear/PEAR.php', '/controllers/admin/AdminLoginController.php', '/css/index.php', @@ -94,6 +94,7 @@ class ConfigurationTestCore 'upload_max_filesize' => false, 'max_execution_time' => false, 'fopen' => false, + 'zip' => false, )); } @@ -179,7 +180,7 @@ class ConfigurationTestCore public static function test_magicquotes() { - return !get_magic_quotes_gpc(); + return function_exists('get_magic_quotes_gpc') ? !get_magic_quotes_gpc() : true; } public static function test_upload() @@ -214,6 +215,12 @@ class ConfigurationTestCore return false; } + public static function test_zip() + { + return extension_loaded('zip'); + } + + public static function test_fopen() { return ini_get('allow_url_fopen'); diff --git a/classes/Connection.php b/classes/Connection.php index d44729a10..c14ee13fe 100644 --- a/classes/Connection.php +++ b/classes/Connection.php @@ -136,7 +136,7 @@ class ConnectionCore extends ObjectModel '.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER).' ORDER BY `date_add` DESC'; $result = Db::getInstance()->getRow($sql, false); - if (!$result['id_guest'] && (int)$cookie->id_guest) { + if (!isset($result['id_guest']) && (int)$cookie->id_guest) { // The old connections details are removed from the database in order to spare some memory Connection::cleanConnectionsPages(); diff --git a/classes/Cookie.php b/classes/Cookie.php index 6747b0c24..89ee0ef6e 100644 --- a/classes/Cookie.php +++ b/classes/Cookie.php @@ -66,7 +66,7 @@ class CookieCore $this->_standalone = $standalone; $this->_expire = is_null($expire) ? time() + 1728000 : (int)$expire; $this->_path = trim(($this->_standalone ? '' : Context::getContext()->shop->physical_uri).$path, '/\\').'/'; - if ($this->_path{0} != '/') { + if ($this->_path[0] != '/') { $this->_path = '/'.$this->_path; } $this->_path = rawurlencode($this->_path); diff --git a/classes/Language.php b/classes/Language.php index 59f5f2e01..77985d39e 100644 --- a/classes/Language.php +++ b/classes/Language.php @@ -798,7 +798,7 @@ class LanguageCore extends ObjectModel // If the language pack has not been provided, retrieve it from prestashop.com if (!$lang_pack) { - $lang_pack = Tools::jsonDecode(Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/get_language_pack.php?version='._PS_VERSION_.'&iso_lang='.$iso_code)); + $lang_pack = json_decode(Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/get_language_pack.php?version='._PS_VERSION_.'&iso_lang='.$iso_code)); } // If a language pack has been found or provided, prefill the language object with the value @@ -914,7 +914,7 @@ class LanguageCore extends ObjectModel if (!$lang_pack_link = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/get_language_pack.php?version='.$version.'&iso_lang='.Tools::strtolower((string)$iso))) { $errors[] = Tools::displayError('Archive cannot be downloaded from prestashop.com.'); - } elseif (!$lang_pack = Tools::jsonDecode($lang_pack_link)) { + } elseif (!$lang_pack = json_decode($lang_pack_link)) { $errors[] = Tools::displayError('Error occurred when language was checked according to your Prestashop version.'); } elseif (empty($lang_pack->error) && ($content = Tools::file_get_contents('http://translations.prestashop.com/download/lang_packs/gzip/'.$lang_pack->version.'/'.Tools::strtolower($lang_pack->iso_code.'.gzip')))) { if (!@file_put_contents($file, $content)) { @@ -930,7 +930,7 @@ class LanguageCore extends ObjectModel if (!file_exists($file)) { $errors[] = Tools::displayError('No language pack is available for your version.'); } elseif ($install) { - require_once(_PS_TOOL_DIR_.'tar/Archive_Tar.php'); + require_once(_PS_TOOL_DIR_.'tar/Tar.php'); $gz = new Archive_Tar($file, true); $files_list = AdminTranslationsController::filterTranslationFiles(Language::getLanguagePackListContent((string)$iso, $gz)); $files_paths = AdminTranslationsController::filesListToPaths($files_list); @@ -1030,7 +1030,7 @@ class LanguageCore extends ObjectModel public static function updateModulesTranslations(array $modules_list) { - require_once(_PS_TOOL_DIR_.'tar/Archive_Tar.php'); + require_once(_PS_TOOL_DIR_.'tar/Tar.php'); $languages = Language::getLanguages(false); foreach ($languages as $lang) { diff --git a/classes/Product.php b/classes/Product.php index ca3c683bb..1fff837fe 100644 --- a/classes/Product.php +++ b/classes/Product.php @@ -5776,7 +5776,7 @@ class ProductCore extends ObjectModel libxml_use_internal_errors(true); $xml = simplexml_load_string(utf8_decode($postData)); - $roomtypeData = Tools::jsonDecode(Tools::jsonEncode($xml), true); + $roomtypeData = json_decode(json_encode($xml), true); // set room map info for the hotel from request return Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'htl_room_type` (`id_product`, `id_hotel`, `adult`, `children`, `date_add`, `date_upd`) VALUES ('.(int)$this->id.', '.(int) $roomtypeData['room_type']['id_hotel'].', '.(int) $roomtypeData['room_type']['adults'].', '.(int) $roomtypeData['room_type']['children'].', \''.date('Y-m-d h:i:s').'\', \''.date('Y-m-d h:i:s').'\')'); diff --git a/classes/Referrer.php b/classes/Referrer.php index a37ee888c..d6b347669 100644 --- a/classes/Referrer.php +++ b/classes/Referrer.php @@ -236,7 +236,7 @@ class ReferrerCore extends ObjectModel if ($implode) { $sql = 'SELECT COUNT(id_order) AS orders, SUM(total_paid_real / conversion_rate) AS sales FROM '._DB_PREFIX_.'orders - WHERE id_order IN ('.implode($implode, ',').') + WHERE id_order IN ('.implode(',', $implode).') '.Shop::addSqlRestriction(Shop::SHARE_ORDER).' AND valid = 1'; return Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql); @@ -349,6 +349,6 @@ class ReferrerCore extends ObjectModel 'percent_fee' => Tools::displayPrice($stats_sales['sales'] * $referrer->percent_fee / 100, $currency), ); - die('['.Tools::jsonEncode($json_array).']'); + die('['.json_encode($json_array).']'); } } diff --git a/classes/SmartyCacheResourceMysql.php b/classes/Smarty/SmartyCacheResourceMysql.php similarity index 79% rename from classes/SmartyCacheResourceMysql.php rename to classes/Smarty/SmartyCacheResourceMysql.php index c365fd1ff..fd9edd5ad 100644 --- a/classes/SmartyCacheResourceMysql.php +++ b/classes/Smarty/SmartyCacheResourceMysql.php @@ -1,28 +1,28 @@ -* @copyright 2007-2017 PrestaShop SA -* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) -* International Registered Trademark & Property of PrestaShop SA -*/ +/** + * 2007-2017 PrestaShop + * + * NOTICE OF LICENSE + * + * This source file is subject to the Open Software License (OSL 3.0) + * that is bundled with this package in the file LICENSE.txt. + * It is also available through the world-wide-web at this URL: + * http://opensource.org/licenses/osl-3.0.php + * If you did not receive a copy of the license and are unable to + * obtain it through the world-wide-web, please send an email + * to license@prestashop.com so we can send you a copy immediately. + * + * DISCLAIMER + * + * Do not edit or add to this file if you wish to upgrade PrestaShop to newer + * versions in the future. If you wish to customize PrestaShop for your + * needs please refer to http://www.prestashop.com for more information. + * + * @author PrestaShop SA + * @copyright 2007-2017 PrestaShop SA + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * International Registered Trademark & Property of PrestaShop SA + */ require_once(_PS_TOOL_DIR_.'smarty/Smarty.class.php'); diff --git a/classes/SmartyCustom.php b/classes/Smarty/SmartyCustom.php similarity index 92% rename from classes/SmartyCustom.php rename to classes/Smarty/SmartyCustom.php index 1040b59e2..ab022a0bb 100644 --- a/classes/SmartyCustom.php +++ b/classes/Smarty/SmartyCustom.php @@ -1,28 +1,28 @@ -* @copyright 2007-2017 PrestaShop SA -* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) -* International Registered Trademark & Property of PrestaShop SA -*/ +/** + * 2007-2017 PrestaShop + * + * NOTICE OF LICENSE + * + * This source file is subject to the Open Software License (OSL 3.0) + * that is bundled with this package in the file LICENSE.txt. + * It is also available through the world-wide-web at this URL: + * http://opensource.org/licenses/osl-3.0.php + * If you did not receive a copy of the license and are unable to + * obtain it through the world-wide-web, please send an email + * to license@prestashop.com so we can send you a copy immediately. + * + * DISCLAIMER + * + * Do not edit or add to this file if you wish to upgrade PrestaShop to newer + * versions in the future. If you wish to customize PrestaShop for your + * needs please refer to http://www.prestashop.com for more information. + * + * @author PrestaShop SA + * @copyright 2007-2017 PrestaShop SA + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * International Registered Trademark & Property of PrestaShop SA + */ class SmartyCustomCore extends Smarty { diff --git a/classes/Smarty/SmartyDev.php b/classes/Smarty/SmartyDev.php new file mode 100644 index 000000000..e51458ac1 --- /dev/null +++ b/classes/Smarty/SmartyDev.php @@ -0,0 +1,63 @@ + + * @copyright 2007-2016 PrestaShop SA + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * International Registered Trademark & Property of PrestaShop SA + */ + +class SmartyDev extends Smarty +{ + public function __construct() + { + parent::__construct(); + $this->template_class = 'Smarty_Dev_Template'; + } + + /** + * {@inheritDoc} + */ + public function fetch($template = null, $cache_id = null, $compile_id = null, $parent = null, $display = false, $merge_tpl_vars = true, $no_output_filter = false) + { + return "\n\n" + .parent::fetch($template, $cache_id, $compile_id, $parent, $display, $merge_tpl_vars, $no_output_filter) + ."\n\n"; + } +} + +class Smarty_Dev_Template extends Smarty_Internal_Template +{ + /** @var SmartyCustom|null */ + public $smarty = null; + + public function fetch($template = null, $cache_id = null, $compile_id = null, $parent = null, $display = false, $merge_tpl_vars = true, $no_output_filter = false) + { + if (!is_null($template)) { + $tpl = $template->template_resource; + } else { + $tpl = $this->template_resource; + } + + return "\n\n" + .parent::fetch($template, $cache_id, $compile_id, $parent, $display, $merge_tpl_vars, $no_output_filter) + ."\n\n"; + } +} diff --git a/classes/Smarty/SmartyLazyRegister.php b/classes/Smarty/SmartyLazyRegister.php new file mode 100644 index 000000000..c4cc39cf3 --- /dev/null +++ b/classes/Smarty/SmartyLazyRegister.php @@ -0,0 +1,95 @@ + +* @copyright 2007-2015 PrestaShop SA +* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) +* International Registered Trademark & Property of PrestaShop SA +*/ +/** + * Used to delay loading of external classes with smarty->register_plugin. + */ +class SmartyLazyRegister +{ + protected $registry = array(); + protected static $instance; + + /** + * Register a function or method to be dynamically called later. + * + * @param string|array $params function name or array(object name, method name) + */ + public function register($params) + { + if (is_array($params)) { + $this->registry[$params[1]] = $params; + } else { + $this->registry[$params] = $params; + } + } + + public function isRegistered($params) + { + if (is_array($params)) { + $params = $params[1]; + } + + return isset($this->registry[$params]); + } + + /** + * Dynamically call static function or method. + * + * @param string $name function name + * @param mixed $arguments function argument + * + * @return mixed function return + */ + public function __call($name, $arguments) + { + $item = $this->registry[$name]; + + // case 1: call to static method - case 2 : call to static function + if (is_array($item[1])) { + return call_user_func_array($item[1].'::'.$item[0], array($arguments[0], &$arguments[1])); + } else { + $args = array(); + + foreach ($arguments as $a => $argument) { + if ($a == 0) { + $args[] = $arguments[0]; + } else { + $args[] = &$arguments[$a]; + } + } + + return call_user_func_array($item, $args); + } + } + + public static function getInstance() + { + if (!self::$instance) { + self::$instance = new self(); + } + + return self::$instance; + } +} diff --git a/classes/Smarty/SmartyResourceModule.php b/classes/Smarty/SmartyResourceModule.php new file mode 100644 index 000000000..fdbb6c312 --- /dev/null +++ b/classes/Smarty/SmartyResourceModule.php @@ -0,0 +1,68 @@ + + * @copyright 2007-2015 PrestaShop SA + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * International Registered Trademark & Property of PrestaShop SA + */ + +/** + * Override module templates easily + * + * @since 1.7.0.0 + */ +class SmartyResourceModuleCore extends Smarty_Resource_Custom +{ + private $shop; + + public function __construct(array $paths) + { + $this->paths = $paths; + } + + /** + * Fetch a template + * + * @param string $name template name + * @param string $source template source + * @param integer $mtime template modification timestamp (epoch) + * @return void + */ + protected function fetch($name, &$source, &$mtime) + { + foreach ($this->paths as $path) { + if (Tools::file_exists_cache($file = $path.$name)) { + if (_PS_MODE_DEV_) { + $source = implode('', [ + '', + file_get_contents($file), + '' + ]); + } else { + $source = file_get_contents($file); + } + $mtime = filemtime($file); + + return; + } + } + } +} diff --git a/classes/Tools.php b/classes/Tools.php index 7a59a1d8c..2d58fbfae 100644 --- a/classes/Tools.php +++ b/classes/Tools.php @@ -104,65 +104,7 @@ class ToolsCore } } - if (function_exists('mcrypt_create_iv')) { - $bytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); - - if ($bytes !== false && strlen($bytes) === $length) { - return $bytes; - } - } - - // Else try to get $length bytes of entropy. - // Thanks to Zend - - $result = ''; - $entropy = ''; - $msec_per_round = 400; - $bits_per_round = 2; - $total = $length; - $hash_length = 20; - - while (strlen($result) < $length) { - $bytes = ($total > $hash_length) ? $hash_length : $total; - $total -= $bytes; - - for ($i=1; $i < 3; $i++) { - $t1 = microtime(true); - $seed = mt_rand(); - - for ($j=1; $j < 50; $j++) { - $seed = sha1($seed); - } - - $t2 = microtime(true); - $entropy .= $t1 . $t2; - } - - $div = (int) (($t2 - $t1) * 1000000); - - if ($div <= 0) { - $div = 400; - } - - $rounds = (int) ($msec_per_round * 50 / $div); - $iter = $bytes * (int) (ceil(8 / $bits_per_round)); - - for ($i = 0; $i < $iter; $i ++) { - $t1 = microtime(); - $seed = sha1(mt_rand()); - - for ($j = 0; $j < $rounds; $j++) { - $seed = sha1($seed); - } - - $t2 = microtime(); - $entropy .= $t1 . $t2; - } - - $result .= sha1($entropy, true); - } - - return substr($result, 0, $length); + return false; } public static function strReplaceFirst($search, $replace, $subject, $cur = 0) @@ -926,6 +868,11 @@ class ToolsCore return html_entity_decode((string)$string, ENT_QUOTES, 'utf-8'); } + public static function removeHtmlComments($html) + { + return preg_replace('//', '', $html); + } + public static function safePostVars() { if (!isset($_POST) || !is_array($_POST)) { @@ -1066,7 +1013,7 @@ class ToolsCore echo ' '; } @@ -1822,10 +1769,10 @@ class ToolsCore return Tools::strtoupper(Tools::substr($str, 0, 1)).Tools::substr($str, 1); } - public static function ucwords($str) + public static function ucwords($str, $encoding = 'utf-8') { if (function_exists('mb_convert_case')) { - return mb_convert_case($str, MB_CASE_TITLE); + return mb_convert_case($str, MB_CASE_TITLE, $encoding); } return ucwords(Tools::strtolower($str)); } @@ -2222,8 +2169,8 @@ class ToolsCore public static function parserSQL($sql) { if (strlen($sql) > 0) { - require_once _PS_TOOL_DIR_.'parser_sql/PHPSQLParser.php'; - $parser = new PHPSQLParser($sql); + require_once _PS_TOOL_DIR_.'parser_sql/php_sql_parser_autoload.php'; + $parser = new PHPSQLParser\PHPSQLParser($sql); return $parser->parsed; } return false; @@ -2660,19 +2607,15 @@ exit; /** * jsonDecode convert json string to php array / object * - * @param string $json + * @param string $data * @param bool $assoc (since 1.4.2.4) if true, convert to associativ array * @return array */ - public static function jsonDecode($json, $assoc = false) + public static function jsonDecode($data, $assoc = false, $depth = 512, $options = 0 + ) { - if (function_exists('json_decode')) { - return json_decode($json, $assoc); - } else { - include_once(_PS_TOOL_DIR_.'json/json.php'); - $pear_json = new Services_JSON(($assoc) ? SERVICES_JSON_LOOSE_TYPE : 0); - return $pear_json->decode($json); - } + Tools::displayAsDeprecated(); + return json_decode($data, $assoc, $depth, $options); } /** @@ -2681,15 +2624,15 @@ exit; * @param array $data * @return string json */ - public static function jsonEncode($data) + public static function jsonEncode($data, $options = 0, $depth = 512) { - if (function_exists('json_encode')) { - return json_encode($data); - } else { - include_once(_PS_TOOL_DIR_.'json/json.php'); - $pear_json = new Services_JSON(); - return $pear_json->encode($data); + Tools::displayAsDeprecated(); + if (PHP_VERSION_ID < 50500) { /* PHP version < 5.5.0 */ + return json_encode($data, $options); } + + return json_encode($data, $options, $depth); + } /** @@ -2854,14 +2797,9 @@ exit; */ public static function ZipTest($from_file) { - if (class_exists('ZipArchive', false)) { - $zip = new ZipArchive(); - return ($zip->open($from_file, ZIPARCHIVE::CHECKCONS) === true); - } else { - require_once(_PS_ROOT_DIR_.'/tools/pclzip/pclzip.lib.php'); - $zip = new PclZip($from_file); - return ($zip->privCheckFormat() === true); - } + $zip = new ZipArchive(); + + return ($zip->open($from_file, ZipArchive::CHECKCONS) === true); } public static function getSafeModeStatus() @@ -2881,23 +2819,12 @@ exit; if (!file_exists($to_dir)) { mkdir($to_dir, 0777); } - if (class_exists('ZipArchive', false)) { - $zip = new ZipArchive(); - if ($zip->open($from_file) === true && $zip->extractTo($to_dir) && $zip->close()) { - return true; - } - return false; - } else { - require_once(_PS_ROOT_DIR_.'/tools/pclzip/pclzip.lib.php'); - $zip = new PclZip($from_file); - $list = $zip->extract(PCLZIP_OPT_PATH, $to_dir, PCLZIP_OPT_REPLACE_NEWER); - foreach ($list as $file) { - if ($file['status'] != 'ok' && $file['status'] != 'already_a_directory') { - return false; - } - } + $zip = new ZipArchive(); + if ($zip->open($from_file) === true && $zip->extractTo($to_dir) && $zip->close()) { return true; } + + return false; } public static function chmodr($path, $filemode) @@ -3626,8 +3553,6 @@ exit; public static function purifyHTML($html, $uri_unescape = null, $allow_style = false) { - require_once(_PS_TOOL_DIR_.'htmlpurifier/HTMLPurifier.standalone.php'); - static $use_html_purifier = null; static $purifier = null; diff --git a/classes/controller/AdminController.php b/classes/controller/AdminController.php index 6bc800a5f..650355110 100644 --- a/classes/controller/AdminController.php +++ b/classes/controller/AdminController.php @@ -1803,14 +1803,14 @@ class AdminControllerCore extends Controller } if ($conf = Tools::getValue('conf')) { - $this->context->smarty->assign('conf', $this->json ? Tools::jsonEncode($this->_conf[(int)$conf]) : $this->_conf[(int)$conf]); + $this->context->smarty->assign('conf', $this->json ? json_encode($this->_conf[(int)$conf]) : $this->_conf[(int)$conf]); } foreach (array('errors', 'warnings', 'informations', 'confirmations') as $type) { if (!is_array($this->$type)) { $this->$type = (array)$this->$type; } - $this->context->smarty->assign($type, $this->json ? Tools::jsonEncode(array_unique($this->$type)) : array_unique($this->$type)); + $this->context->smarty->assign($type, $this->json ? json_encode(array_unique($this->$type)) : array_unique($this->$type)); } if ($this->show_page_header_toolbar && !$this->lite_display) { @@ -1824,7 +1824,7 @@ class AdminControllerCore extends Controller $this->context->smarty->assign( array( - 'page' => $this->json ? Tools::jsonEncode($page) : $page, + 'page' => $this->json ? json_encode($page) : $page, 'header' => $this->context->smarty->fetch($header_tpl), 'footer' => $this->context->smarty->fetch($footer_tpl), ) diff --git a/classes/helper/HelperList.php b/classes/helper/HelperList.php index 0686a9dcf..c6e2dbcbb 100644 --- a/classes/helper/HelperList.php +++ b/classes/helper/HelperList.php @@ -435,7 +435,7 @@ class HelperListCore extends Helper 'token' => $token != null ? $token : $this->token, 'action' => self::$cache_lang['Details'], 'params' => $ajax_params, - 'json_params' => Tools::jsonEncode($ajax_params) + 'json_params' => json_encode($ajax_params) )); return $tpl->fetch(); } diff --git a/classes/pdf/HTMLTemplateInvoice.php b/classes/pdf/HTMLTemplateInvoice.php index 15a2eda93..befe153e7 100644 --- a/classes/pdf/HTMLTemplateInvoice.php +++ b/classes/pdf/HTMLTemplateInvoice.php @@ -142,8 +142,8 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate */ public function getContent() { - $invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true); - $deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true); + $invoiceAddressPatternRules = json_decode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true); + $deliveryAddressPatternRules = json_decode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true); $invoice_address = new Address((int)$this->order->id_address_invoice); $country = new Country((int)$invoice_address->id_country); @@ -444,8 +444,8 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate $num_days = $obj_htl_bk_dtl->getNumberOfDays($data_v['date_from'], $data_v['date_to']); $cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] = 1; - $cart_htl_data[$type_key]['date_diff'][$date_join]['data_form'] = $data_v['date_from']; - $cart_htl_data[$type_key]['date_diff'][$date_join]['data_to'] = $data_v['date_to']; + $cart_htl_data[$type_key]['date_diff'][$date_join]['data_form'] = Tools::displayDate($data_v['date_from']); + $cart_htl_data[$type_key]['date_diff'][$date_join]['data_to'] = Tools::displayDate($data_v['date_to']); $cart_htl_data[$type_key]['date_diff'][$date_join]['num_days'] = $num_days; $cart_htl_data[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_excl'] = $data_v['total_price_tax_excl']/$num_days; diff --git a/classes/pdf/PDFGenerator.php b/classes/pdf/PDFGenerator.php index e16cc3a25..4cd27a6bb 100644 --- a/classes/pdf/PDFGenerator.php +++ b/classes/pdf/PDFGenerator.php @@ -24,7 +24,6 @@ * International Registered Trademark & Property of PrestaShop SA */ -require_once(_PS_TOOL_DIR_.'tcpdf/config/lang/eng.php'); require_once(_PS_TOOL_DIR_.'tcpdf/tcpdf.php'); /** diff --git a/classes/tree/TreeToolbarSearch.php b/classes/tree/TreeToolbarSearch.php index 417023e50..edfb693cf 100644 --- a/classes/tree/TreeToolbarSearch.php +++ b/classes/tree/TreeToolbarSearch.php @@ -76,7 +76,7 @@ class TreeToolbarSearchCore extends TreeToolbarButtonCore implements $html = ''; foreach ($data as $item) { - $html .= Tools::jsonEncode($item).','; + $html .= json_encode($item).','; if (array_key_exists('children', $item) && !empty($item['children'])) { $html .= $this->_renderData($item['children']); } diff --git a/classes/tree/TreeToolbarSearchCategories.php b/classes/tree/TreeToolbarSearchCategories.php index 2a6f93d66..a00f387de 100644 --- a/classes/tree/TreeToolbarSearchCategories.php +++ b/classes/tree/TreeToolbarSearchCategories.php @@ -73,7 +73,7 @@ class TreeToolbarSearchCategoriesCore extends TreeToolbarButtonCore implements $html = ''; foreach ($data as $item) { - $html .= Tools::jsonEncode($item).','; + $html .= json_encode($item).','; if (array_key_exists('children', $item) && !empty($item['children'])) { $html .= $this->_renderData($item['children']); } diff --git a/config/config.inc.php b/config/config.inc.php index d362ffb20..c9b3f60ca 100644 --- a/config/config.inc.php +++ b/config/config.inc.php @@ -132,7 +132,7 @@ define('_PS_PRICE_DISPLAY_PRECISION_', Configuration::get('PS_PRICE_DISPLAY_PREC define('_PS_PRICE_COMPUTE_PRECISION_', _PS_PRICE_DISPLAY_PRECISION_); if (Configuration::get('PS_USE_HTMLPURIFIER')) { - require_once(_PS_TOOL_DIR_.'htmlpurifier/HTMLPurifier.standalone.php'); + require_once(_PS_TOOL_DIR_.'htmlpurifier/HTMLPurifier.auto.php'); } /* Load all languages */ diff --git a/config/defines.inc.php b/config/defines.inc.php index 44ec5711d..899b1a0a8 100644 --- a/config/defines.inc.php +++ b/config/defines.inc.php @@ -140,7 +140,7 @@ define('_PS_TMP_IMG_DIR_', _PS_IMG_DIR_.'tmp/'); define('_PS_TRANS_PATTERN_', '(.*[^\\\\])'); define('_PS_MIN_TIME_GENERATE_PASSWD_', '360'); if (!defined('_PS_MAGIC_QUOTES_GPC_')) { - define('_PS_MAGIC_QUOTES_GPC_', get_magic_quotes_gpc()); + define('_PS_MAGIC_QUOTES_GPC_', function_exists('get_magic_quotes_gpc')? @get_magic_quotes_gpc() : false); } define('_CAN_LOAD_FILES_', 1); diff --git a/config/smarty.config.inc.php b/config/smarty.config.inc.php index 0a2bd64ba..286403d39 100644 --- a/config/smarty.config.inc.php +++ b/config/smarty.config.inc.php @@ -29,7 +29,14 @@ define('_PS_SMARTY_DIR_', _PS_TOOL_DIR_.'smarty/'); require_once(_PS_SMARTY_DIR_.'Smarty.class.php'); global $smarty; -$smarty = new SmartyCustom(); +if (Configuration::get('PS_SMARTY_LOCAL')) { + $smarty = new SmartyCustom(); +} elseif (_PS_MODE_DEV_) { + $smarty = new SmartyDev(); +} else { + $smarty = new Smarty(); +} + $smarty->setCompileDir(_PS_CACHE_DIR_.'smarty/compile'); $smarty->setCacheDir(_PS_CACHE_DIR_.'smarty/cache'); if (!Tools::getSafeModeStatus()) { @@ -38,7 +45,7 @@ if (!Tools::getSafeModeStatus()) { $smarty->setConfigDir(_PS_SMARTY_DIR_.'configs'); $smarty->caching = false; if (Configuration::get('PS_SMARTY_CACHING_TYPE') == 'mysql') { - include(_PS_CLASS_DIR_.'/SmartyCacheResourceMysql.php'); + include _PS_CLASS_DIR_.'Smarty/SmartyCacheResourceMysql.php'; $smarty->caching_type = 'mysql'; } $smarty->force_compile = (Configuration::get('PS_SMARTY_FORCE_COMPILE') == _PS_SMARTY_FORCE_COMPILE_) ? true : false; @@ -55,7 +62,27 @@ if (defined('_PS_ADMIN_DIR_')) { } else { require_once(dirname(__FILE__).'/smartyfront.config.inc.php'); } +require_once SMARTY_PLUGINS_DIR.'modifier.truncate.php'; +// This escape modifier is required for invoice PDF generation +function smartyEscape($string, $esc_type = 'html', $char_set = null, $double_encode = true) +{ + $escapeModifierFile = implode( + DIRECTORY_SEPARATOR, + array( + SMARTY_PLUGINS_DIR, + 'modifier.escape.php', + ) + ); + require_once $escapeModifierFile; + + global $smarty; + if (($esc_type === 'html' || $esc_type === 'htmlall') && $smarty->escape_html) { + return $string; + } else { + return smarty_modifier_escape($string, $esc_type, $char_set, $double_encode); + } +} smartyRegisterFunction($smarty, 'modifier', 'truncate', 'smarty_modifier_truncate'); smartyRegisterFunction($smarty, 'modifier', 'secureReferrer', array('Tools', 'secureReferrer')); @@ -123,25 +150,6 @@ function smartyTruncate($params, &$smarty) return (isset($params['encode']) ? Tools::htmlentitiesUTF8($text, ENT_NOQUOTES) : $text); } -function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false, $charset = 'UTF-8') -{ - if (!$length) { - return ''; - } - - $string = trim($string); - - if (Tools::strlen($string) > $length) { - $length -= min($length, Tools::strlen($etc)); - if (!$break_words && !$middle) { - $string = preg_replace('/\s+?(\S+)?$/u', '', Tools::substr($string, 0, $length+1, $charset)); - } - return !$middle ? Tools::substr($string, 0, $length, $charset).$etc : Tools::substr($string, 0, $length/2, $charset).$etc.Tools::substr($string, -$length/2, $length, $charset); - } else { - return $string; - } -} - function smarty_modifier_htmlentitiesUTF8($string) { return Tools::htmlentitiesUTF8($string); @@ -175,6 +183,9 @@ function smartyRegisterFunction($smarty, $type, $function, $params, $lazy = true // lazy is better if the function is not called on every page if ($lazy) { $lazy_register = SmartyLazyRegister::getInstance(); + if ($lazy_register->isRegistered($params)) { + return; + } $lazy_register->register($params); if (is_array($params)) { @@ -221,61 +232,3 @@ function toolsConvertPrice($params, &$smarty) return Tools::convertPrice($params['price'], Context::getContext()->currency); } -/** - * Used to delay loading of external classes with smarty->register_plugin - */ -class SmartyLazyRegister -{ - protected $registry = array(); - protected static $instance; - - /** - * Register a function or method to be dynamically called later - * @param string|array $params function name or array(object name, method name) - */ - public function register($params) - { - if (is_array($params)) { - $this->registry[$params[1]] = $params; - } else { - $this->registry[$params] = $params; - } - } - - /** - * Dynamically call static function or method - * - * @param string $name function name - * @param mixed $arguments function argument - * @return mixed function return - */ - public function __call($name, $arguments) - { - $item = $this->registry[$name]; - - // case 1: call to static method - case 2 : call to static function - if (is_array($item[1])) { - return call_user_func_array($item[1].'::'.$item[0], array($arguments[0], &$arguments[1])); - } else { - $args = array(); - - foreach ($arguments as $a => $argument) { - if ($a == 0) { - $args[] = $arguments[0]; - } else { - $args[] = &$arguments[$a]; - } - } - - return call_user_func_array($item, $args); - } - } - - public static function getInstance() - { - if (!self::$instance) { - self::$instance = new SmartyLazyRegister(); - } - return self::$instance; - } -} diff --git a/config/smartyadmin.config.inc.php b/config/smartyadmin.config.inc.php index 47475fcf2..f8c8a270c 100644 --- a/config/smartyadmin.config.inc.php +++ b/config/smartyadmin.config.inc.php @@ -33,7 +33,7 @@ $smarty->force_compile = (Configuration::get('PS_SMARTY_FORCE_COMPILE') == _PS_S // But force compile_check since the performance impact is small and it is better for debugging $smarty->compile_check = true; -function smartyTranslate($params, &$smarty) +function smartyTranslate($params, $smarty) { $htmlentities = !isset($params['js']); $pdf = isset($params['pdf']); diff --git a/config/smartyfront.config.inc.php b/config/smartyfront.config.inc.php index 90773929a..c9afef57d 100644 --- a/config/smartyfront.config.inc.php +++ b/config/smartyfront.config.inc.php @@ -25,7 +25,7 @@ */ global $smarty; -$smarty->setTemplateDir(_PS_THEME_DIR_.'tpl'); +$smarty->setTemplateDir(_PS_THEME_DIR_); if (Configuration::get('PS_HTML_THEME_COMPRESSION')) { $smarty->registerFilter('output', 'smartyMinifyHTML'); @@ -34,7 +34,7 @@ if (Configuration::get('PS_JS_HTML_THEME_COMPRESSION')) { $smarty->registerFilter('output', 'smartyPackJSinHTML'); } -function smartyTranslate($params, &$smarty) +function smartyTranslate($params, $smarty) { global $_LANG; @@ -48,7 +48,47 @@ function smartyTranslate($params, &$smarty) $params['mod'] = false; } if (!isset($params['sprintf'])) { - $params['sprintf'] = null; + $params['sprintf'] = array(); + } + + if (!isset($params['d'])) { + $params['d'] = null; + } + + if (!is_null($params['d'])) { + if (isset($params['tags'])) { + $backTrace = debug_backtrace(); + + $errorMessage = sprintf( + 'Unable to translate "%s" in %s. tags() is not supported anymore, please use sprintf().', + $params['s'], + $backTrace[0]['args'][1]->template_resource + ); + + if (_PS_MODE_DEV_) { + throw new Exception($errorMessage); + } else { + PrestaShopLogger::addLog($errorMessage); + } + } + + if (!is_array($params['sprintf'])) { + $backTrace = debug_backtrace(); + + $errorMessage = sprintf( + 'Unable to translate "%s" in %s. sprintf() parameter should be an array.', + $params['s'], + $backTrace[0]['args'][1]->template_resource + ); + + if (_PS_MODE_DEV_) { + throw new Exception($errorMessage); + } else { + PrestaShopLogger::addLog($errorMessage); + + return $params['s']; + } + } } $string = str_replace('\'', '\\\'', $params['s']); diff --git a/controllers/admin/AdminAddressesController.php b/controllers/admin/AdminAddressesController.php index c57e24b1e..ce37b1743 100644 --- a/controllers/admin/AdminAddressesController.php +++ b/controllers/admin/AdminAddressesController.php @@ -495,7 +495,7 @@ class AdminAddressesControllerCore extends AdminController $customer = Customer::searchByName($email); if (!empty($customer)) { $customer = $customer['0']; - echo Tools::jsonEncode(array('infos' => pSQL($customer['firstname']).'_'.pSQL($customer['lastname']).'_'.pSQL($customer['company']))); + echo json_encode(array('infos' => pSQL($customer['firstname']).'_'.pSQL($customer['lastname']).'_'.pSQL($customer['company']))); } } die; diff --git a/controllers/admin/AdminAttributeGeneratorController.php b/controllers/admin/AdminAttributeGeneratorController.php index 7c3a69900..8eac6b357 100644 --- a/controllers/admin/AdminAttributeGeneratorController.php +++ b/controllers/admin/AdminAttributeGeneratorController.php @@ -76,7 +76,7 @@ class AdminAttributeGeneratorControllerCore extends AdminController protected static function createCombinations($list) { if (count($list) <= 1) { - return count($list) ? array_map(create_function('$v', 'return (array($v));'), $list[0]) : $list; + return count($list) ? array_map(function ($v) {return (array($v));}, $list[0]) : $list; } $res = array(); $first = array_pop($list); diff --git a/controllers/admin/AdminAttributesGroupsController.php b/controllers/admin/AdminAttributesGroupsController.php index 19e8c55c0..c47cb31e3 100644 --- a/controllers/admin/AdminAttributesGroupsController.php +++ b/controllers/admin/AdminAttributesGroupsController.php @@ -297,7 +297,7 @@ class AdminAttributesGroupsControllerCore extends AdminController $associations = array(); } - $this->fields_form['shop_associations'] = Tools::jsonEncode($associations); + $this->fields_form['shop_associations'] = json_encode($associations); $this->fields_form['input'][] = array( 'type' => 'color', diff --git a/controllers/admin/AdminCarrierWizardController.php b/controllers/admin/AdminCarrierWizardController.php index e5057a4ec..c00efd707 100644 --- a/controllers/admin/AdminCarrierWizardController.php +++ b/controllers/admin/AdminCarrierWizardController.php @@ -652,7 +652,7 @@ class AdminCarrierWizardControllerCore extends AdminController $return['errors'] = $this->errors; } if (count($this->errors) || $die) { - die(Tools::jsonEncode($return)); + die(json_encode($return)); } } @@ -870,7 +870,7 @@ class AdminCarrierWizardControllerCore extends AdminController $return['id_carrier'] = $carrier->id; } } - die(Tools::jsonEncode($return)); + die(json_encode($return)); } protected function changeGroups($id_carrier, $delete = true) diff --git a/controllers/admin/AdminCartRulesController.php b/controllers/admin/AdminCartRulesController.php index 9dccbb5db..87509df72 100644 --- a/controllers/admin/AdminCartRulesController.php +++ b/controllers/admin/AdminCartRulesController.php @@ -140,7 +140,7 @@ class AdminCartRulesControllerCore extends AdminController } } } - echo Tools::jsonEncode(array('html' => $html, 'next_link' => $next_link)); + echo json_encode(array('html' => $html, 'next_link' => $next_link)); } public function setMedia() @@ -589,7 +589,7 @@ class AdminCartRulesControllerCore extends AdminController ) ORDER BY c.`firstname`, c.`lastname` ASC LIMIT 50'); - die(Tools::jsonEncode($customers)); + die(json_encode($customers)); } // Both product filter (free product and product discount) search for products if (Tools::isSubmit('giftProductFilter') || Tools::isSubmit('reductionProductFilter')) { @@ -599,7 +599,7 @@ class AdminCartRulesControllerCore extends AdminController $products, $this->context->employee->id_profile ); - die(Tools::jsonEncode($products)); + die(json_encode($products)); } } @@ -642,7 +642,7 @@ class AdminCartRulesControllerCore extends AdminController public function ajaxProcessSearchProducts() { $array = $this->searchProducts(Tools::getValue('product_search')); - $this->content = trim(Tools::jsonEncode($array)); + $this->content = trim(json_encode($array)); } public function renderForm() @@ -771,6 +771,6 @@ class AdminCartRulesControllerCore extends AdminController if ($vouchers = CartRule::getCartsRuleByCode(Tools::getValue('q'), (int)$this->context->language->id, true)) { $found = true; } - echo Tools::jsonEncode(array('found' => $found, 'vouchers' => $vouchers)); + echo json_encode(array('found' => $found, 'vouchers' => $vouchers)); } } diff --git a/controllers/admin/AdminCartsController.php b/controllers/admin/AdminCartsController.php index cea2b24b6..ebd03b7a4 100644 --- a/controllers/admin/AdminCartsController.php +++ b/controllers/admin/AdminCartsController.php @@ -403,10 +403,10 @@ class AdminCartsControllerCore extends AdminController $errors[] = Tools::displayError('Invalid combination'); } if (count($errors)) { - die(Tools::jsonEncode($errors)); + die(json_encode($errors)); } if ($this->context->cart->deleteProduct($id_product, $id_product_attribute, (int)Tools::getValue('id_customization'))) { - echo Tools::jsonEncode($this->ajaxReturnVars()); + echo json_encode($this->ajaxReturnVars()); } } } @@ -520,7 +520,7 @@ class AdminCartsControllerCore extends AdminController } } - echo Tools::jsonEncode(array_merge($this->ajaxReturnVars(), array('errors' => $errors))); + echo json_encode(array_merge($this->ajaxReturnVars(), array('errors' => $errors))); } } @@ -541,7 +541,7 @@ class AdminCartsControllerCore extends AdminController $this->context->cart->gift_message = $gift_message; } $this->context->cart->save(); - echo Tools::jsonEncode($this->ajaxReturnVars()); + echo json_encode($this->ajaxReturnVars()); } } @@ -563,7 +563,7 @@ class AdminCartsControllerCore extends AdminController } elseif (Validate::isLoadedObject($message)) { $message->delete(); } - echo Tools::jsonEncode($this->ajaxReturnVars()); + echo json_encode($this->ajaxReturnVars()); } } @@ -593,7 +593,7 @@ class AdminCartsControllerCore extends AdminController $result = $this->ajaxReturnVars(); $result['cart_detail_html'] = $cart_dtl_tpl;//tpl is added to the returned array - echo Tools::jsonEncode($result); + echo json_encode($result); } } public function ajaxProcessUpdateLang() @@ -604,7 +604,7 @@ class AdminCartsControllerCore extends AdminController $this->context->cart->id_lang = (int)$lang->id; $this->context->cart->save(); } - echo Tools::jsonEncode($this->ajaxReturnVars()); + echo json_encode($this->ajaxReturnVars()); } } @@ -623,7 +623,7 @@ class AdminCartsControllerCore extends AdminController $errors[] = Tools::displayError('The order cannot be renewed.'); } else { $this->context->cart = $new_cart['cart']; - echo Tools::jsonEncode($this->ajaxReturnVars()); + echo json_encode($this->ajaxReturnVars()); } } } @@ -632,7 +632,7 @@ class AdminCartsControllerCore extends AdminController { if ($this->tabAccess['edit'] === '1') { if ($this->context->cart->removeCartRule((int)Tools::getValue('id_cart_rule'))) { - echo Tools::jsonEncode($this->ajaxReturnVars()); + echo json_encode($this->ajaxReturnVars()); } } } @@ -663,7 +663,7 @@ class AdminCartsControllerCore extends AdminController $this->context->cart->addCartRule((int)$cart_rule->id); } - echo Tools::jsonEncode($this->ajaxReturnVars()); + echo json_encode($this->ajaxReturnVars()); } } @@ -681,14 +681,14 @@ class AdminCartsControllerCore extends AdminController $errors[] = Tools::displayError('Can\'t add the voucher.'); } } - echo Tools::jsonEncode(array_merge($this->ajaxReturnVars(), array('errors' => $errors))); + echo json_encode(array_merge($this->ajaxReturnVars(), array('errors' => $errors))); } } public function ajaxProcessUpdateAddress() { if ($this->tabAccess['edit'] === '1') { - echo Tools::jsonEncode(array('addresses' => $this->context->customer->getAddresses((int)$this->context->cart->id_lang))); + echo json_encode(array('addresses' => $this->context->customer->getAddresses((int)$this->context->cart->id_lang))); } } @@ -709,7 +709,7 @@ class AdminCartsControllerCore extends AdminController /*$this->context->cart->id_address_invoice = (int)$address_invoice->id;*/ $this->context->cart->save(); - echo Tools::jsonEncode($this->ajaxReturnVars()); + echo json_encode($this->ajaxReturnVars()); } } @@ -825,7 +825,7 @@ class AdminCartsControllerCore extends AdminController $to_return = array_merge($this->ajaxReturnVars(), array('found' => false)); } - echo Tools::jsonEncode($to_return); + echo json_encode($to_return); } public function ajaxReturnVars() @@ -879,7 +879,7 @@ class AdminCartsControllerCore extends AdminController public function displayAjaxGetSummary() { - echo Tools::jsonEncode($this->ajaxReturnVars()); + echo json_encode($this->ajaxReturnVars()); } public function ajaxProcessUpdateProductPrice() @@ -903,7 +903,7 @@ class AdminCartsControllerCore extends AdminController $specific_price->from = '0000-00-00 00:00:00'; $specific_price->to = '0000-00-00 00:00:00'; $specific_price->add(); - echo Tools::jsonEncode($this->ajaxReturnVars()); + echo json_encode($this->ajaxReturnVars()); } } diff --git a/controllers/admin/AdminCategoriesController.php b/controllers/admin/AdminCategoriesController.php index 999f85bf8..4d8d9c922 100644 --- a/controllers/admin/AdminCategoriesController.php +++ b/controllers/admin/AdminCategoriesController.php @@ -961,14 +961,14 @@ class AdminCategoriesControllerCore extends AdminController public function ajaxProcessStatusCategory() { if (!$id_category = (int)Tools::getValue('id_category')) { - die(Tools::jsonEncode(array('success' => false, 'error' => true, 'text' => $this->l('Failed to update the status')))); + die(json_encode(array('success' => false, 'error' => true, 'text' => $this->l('Failed to update the status')))); } else { $category = new Category((int)$id_category); if (Validate::isLoadedObject($category)) { $category->active = $category->active == 1 ? 0 : 1; $category->save() ? - die(Tools::jsonEncode(array('success' => true, 'text' => $this->l('The status has been updated successfully')))) : - die(Tools::jsonEncode(array('success' => false, 'error' => true, 'text' => $this->l('Failed to update the status')))); + die(json_encode(array('success' => true, 'text' => $this->l('The status has been updated successfully')))) : + die(json_encode(array('success' => false, 'error' => true, 'text' => $this->l('Failed to update the status')))); } } } diff --git a/controllers/admin/AdminCustomerThreadsController.php b/controllers/admin/AdminCustomerThreadsController.php index 53689d797..fa01f8cbc 100644 --- a/controllers/admin/AdminCustomerThreadsController.php +++ b/controllers/admin/AdminCustomerThreadsController.php @@ -896,7 +896,7 @@ class AdminCustomerThreadsControllerCore extends AdminController } if (Tools::isSubmit('syncImapMail')) { - die(Tools::jsonEncode($this->syncImap())); + die(json_encode($this->syncImap())); } } diff --git a/controllers/admin/AdminCustomersController.php b/controllers/admin/AdminCustomersController.php index 1721be4c5..3150be406 100644 --- a/controllers/admin/AdminCustomersController.php +++ b/controllers/admin/AdminCustomersController.php @@ -1104,7 +1104,7 @@ class AdminCustomersControllerCore extends AdminController $to_return = array('found' => false); } - $this->content = Tools::jsonEncode($to_return); + $this->content = json_encode($to_return); } /** diff --git a/controllers/admin/AdminDashboardController.php b/controllers/admin/AdminDashboardController.php index 00a845e0f..ebb22ce89 100644 --- a/controllers/admin/AdminDashboardController.php +++ b/controllers/admin/AdminDashboardController.php @@ -370,7 +370,7 @@ class AdminDashboardControllerCore extends AdminController 'extra' => (int)Tools::getValue('extra') ); - die(Tools::jsonEncode(Hook::exec('dashboardData', $params, $id_module, true, true, (int)Tools::getValue('dashboard_use_push')))); + die(json_encode(Hook::exec('dashboardData', $params, $id_module, true, true, (int)Tools::getValue('dashboard_use_push')))); } public function ajaxProcessSetSimulationMode() @@ -437,7 +437,7 @@ class AdminDashboardControllerCore extends AdminController } } } - die(Tools::jsonEncode($return)); + die(json_encode($return)); } public function ajaxProcessSaveDashConfig() @@ -475,6 +475,6 @@ class AdminDashboardControllerCore extends AdminController $return['widget_html'] = $module_obj->$hook($params); } - die(Tools::jsonEncode($return)); + die(json_encode($return)); } } diff --git a/controllers/admin/AdminEmployeesController.php b/controllers/admin/AdminEmployeesController.php index 6453095b7..44ab21028 100644 --- a/controllers/admin/AdminEmployeesController.php +++ b/controllers/admin/AdminEmployeesController.php @@ -673,6 +673,6 @@ class AdminEmployeesControllerCore extends AdminController } } } - die(Tools::jsonEncode($this->tabs_list)); + die(json_encode($this->tabs_list)); } } diff --git a/controllers/admin/AdminGroupsController.php b/controllers/admin/AdminGroupsController.php index 72353abde..6762d8f18 100644 --- a/controllers/admin/AdminGroupsController.php +++ b/controllers/admin/AdminGroupsController.php @@ -451,7 +451,7 @@ class AdminGroupsControllerCore extends AdminController $result['discount'] = $category_reduction; $result['hasError'] = false; } - die(Tools::jsonEncode($result)); + die(json_encode($result)); } /** diff --git a/controllers/admin/AdminImagesController.php b/controllers/admin/AdminImagesController.php index 11bd67be4..11ce68c13 100644 --- a/controllers/admin/AdminImagesController.php +++ b/controllers/admin/AdminImagesController.php @@ -58,9 +58,9 @@ class AdminImagesControllerCore extends AdminController 'height' => array('title' => $this->l('Height'), 'suffix' => ' px'), 'products' => array('title' => $this->l('Products'), 'align' => 'center', 'type' => 'bool', 'callback' => 'printEntityActiveIcon', 'orderby' => false), 'categories' => array('title' => $this->l('Categories'), 'align' => 'center', 'type' => 'bool', 'callback' => 'printEntityActiveIcon', 'orderby' => false), - 'manufacturers' => array('title' => $this->l('Manufacturers'), 'align' => 'center', 'type' => 'bool', 'callback' => 'printEntityActiveIcon', 'orderby' => false), - 'suppliers' => array('title' => $this->l('Suppliers'), 'align' => 'center', 'type' => 'bool', 'callback' => 'printEntityActiveIcon', 'orderby' => false), - 'stores' => array('title' => $this->l('Stores'), 'align' => 'center', 'type' => 'bool', 'callback' => 'printEntityActiveIcon', 'orderby' => false) + // 'manufacturers' => array('title' => $this->l('Manufacturers'), 'align' => 'center', 'type' => 'bool', 'callback' => 'printEntityActiveIcon', 'orderby' => false), + // 'suppliers' => array('title' => $this->l('Suppliers'), 'align' => 'center', 'type' => 'bool', 'callback' => 'printEntityActiveIcon', 'orderby' => false), + // 'stores' => array('title' => $this->l('Stores'), 'align' => 'center', 'type' => 'bool', 'callback' => 'printEntityActiveIcon', 'orderby' => false) ); // Scenes tab has been removed by default from the installation, but may still exists in updates @@ -267,46 +267,46 @@ class AdminImagesControllerCore extends AdminController ), ) ), - array( - 'type' => 'switch', - 'label' => $this->l('Manufacturers'), - 'name' => 'manufacturers', - 'required' => false, - 'is_bool' => true, - 'hint' => $this->l('This type will be used for Manufacturer images.'), - 'values' => array( - array( - 'id' => 'manufacturers_on', - 'value' => 1, - 'label' => $this->l('Enabled') - ), - array( - 'id' => 'manufacturers_off', - 'value' => 0, - 'label' => $this->l('Disabled') - ), - ) - ), - array( - 'type' => 'switch', - 'label' => $this->l('Suppliers'), - 'name' => 'suppliers', - 'required' => false, - 'is_bool' => true, - 'hint' => $this->l('This type will be used for Supplier images.'), - 'values' => array( - array( - 'id' => 'suppliers_on', - 'value' => 1, - 'label' => $this->l('Enabled') - ), - array( - 'id' => 'suppliers_off', - 'value' => 0, - 'label' => $this->l('Disabled') - ), - ) - ), + // array( + // 'type' => 'switch', + // 'label' => $this->l('Manufacturers'), + // 'name' => 'manufacturers', + // 'required' => false, + // 'is_bool' => true, + // 'hint' => $this->l('This type will be used for Manufacturer images.'), + // 'values' => array( + // array( + // 'id' => 'manufacturers_on', + // 'value' => 1, + // 'label' => $this->l('Enabled') + // ), + // array( + // 'id' => 'manufacturers_off', + // 'value' => 0, + // 'label' => $this->l('Disabled') + // ), + // ) + // ), + // array( + // 'type' => 'switch', + // 'label' => $this->l('Suppliers'), + // 'name' => 'suppliers', + // 'required' => false, + // 'is_bool' => true, + // 'hint' => $this->l('This type will be used for Supplier images.'), + // 'values' => array( + // array( + // 'id' => 'suppliers_on', + // 'value' => 1, + // 'label' => $this->l('Enabled') + // ), + // array( + // 'id' => 'suppliers_off', + // 'value' => 0, + // 'label' => $this->l('Disabled') + // ), + // ) + // ), array( 'type' => 'switch', 'label' => $this->l('Scenes'), @@ -328,26 +328,26 @@ class AdminImagesControllerCore extends AdminController ), ) ), - array( - 'type' => 'switch', - 'label' => $this->l('Stores'), - 'name' => 'stores', - 'required' => false, - 'is_bool' => true, - 'hint' => $this->l('This type will be used for Store images.'), - 'values' => array( - array( - 'id' => 'stores_on', - 'value' => 1, - 'label' => $this->l('Enabled') - ), - array( - 'id' => 'stores_off', - 'value' => 0, - 'label' => $this->l('Disabled') - ), - ) - ), + // array( + // 'type' => 'switch', + // 'label' => $this->l('Stores'), + // 'name' => 'stores', + // 'required' => false, + // 'is_bool' => true, + // 'hint' => $this->l('This type will be used for Store images.'), + // 'values' => array( + // array( + // 'id' => 'stores_on', + // 'value' => 1, + // 'label' => $this->l('Enabled') + // ), + // array( + // 'id' => 'stores_off', + // 'value' => 0, + // 'label' => $this->l('Disabled') + // ), + // ) + // ), ), 'submit' => array( 'title' => $this->l('Save') diff --git a/controllers/admin/AdminImportController.php b/controllers/admin/AdminImportController.php index 461ff43a3..be4f42fab 100644 --- a/controllers/admin/AdminImportController.php +++ b/controllers/admin/AdminImportController.php @@ -665,7 +665,7 @@ class AdminImportControllerCore extends AdminController $_FILES['file']['filename'] = $filename_prefix.str_replace('\0', '', $_FILES['file']['name']); } - die(Tools::jsonEncode($_FILES)); + die(json_encode($_FILES)); } public function renderView() diff --git a/controllers/admin/AdminInformationController.php b/controllers/admin/AdminInformationController.php index b8b4648e4..4c820f5e6 100644 --- a/controllers/admin/AdminInformationController.php +++ b/controllers/admin/AdminInformationController.php @@ -170,11 +170,11 @@ class AdminInformationControllerCore extends AdminController $this->file_list = array('missing' => array(), 'updated' => array()); $xml = @simplexml_load_file(_PS_API_URL_.'/xml/md5/'._PS_VERSION_.'.xml'); if (!$xml || !isset($xml->ps_root_dir[0])) { - die(Tools::jsonEncode($this->file_list)); + die(json_encode($this->file_list)); } $this->getListOfUpdatedFiles($xml->ps_root_dir[0]); - die(Tools::jsonEncode($this->file_list)); + die(json_encode($this->file_list)); } public function getListOfUpdatedFiles(SimpleXMLElement $dir, $path = '') diff --git a/controllers/admin/AdminLanguagesController.php b/controllers/admin/AdminLanguagesController.php index 8702fef19..56fca56ad 100644 --- a/controllers/admin/AdminLanguagesController.php +++ b/controllers/admin/AdminLanguagesController.php @@ -543,7 +543,7 @@ class AdminLanguagesControllerCore extends AdminController // Get all iso code available if ($lang_packs = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/get_language_pack.php?version='.Tools::getValue('ps_version').'&iso_lang='.Tools::strtolower(Tools::getValue('iso_lang')))) { - $result = Tools::jsonDecode($lang_packs); + $result = json_decode($lang_packs); if ($lang_packs !== '' && $result && !isset($result->error)) { $this->status = 'ok'; $this->content = $lang_packs; diff --git a/controllers/admin/AdminLoginController.php b/controllers/admin/AdminLoginController.php index 1172dab94..4daeaadf0 100644 --- a/controllers/admin/AdminLoginController.php +++ b/controllers/admin/AdminLoginController.php @@ -219,14 +219,14 @@ class AdminLoginControllerCore extends AdminController } if (Tools::isSubmit('ajax')) { - die(Tools::jsonEncode(array('hasErrors' => false, 'redirect' => $url))); + die(json_encode(array('hasErrors' => false, 'redirect' => $url))); } else { $this->redirect_after = $url; } } } if (Tools::isSubmit('ajax')) { - die(Tools::jsonEncode(array('hasErrors' => true, 'errors' => $this->errors))); + die(json_encode(array('hasErrors' => true, 'errors' => $this->errors))); } } @@ -270,19 +270,19 @@ class AdminLoginControllerCore extends AdminController if (!$result) { $this->errors[] = Tools::displayError('An error occurred while attempting to change your password.'); } else { - die(Tools::jsonEncode(array( + die(json_encode(array( 'hasErrors' => false, 'confirm' => $this->l('Your password has been emailed to you.', 'AdminTab', false, false) ))); } } else { - die(Tools::jsonEncode(array( + die(json_encode(array( 'hasErrors' => true, 'errors' => array(Tools::displayError('An error occurred while attempting to change your password.')) ))); } } elseif (Tools::isSubmit('ajax')) { - die(Tools::jsonEncode(array('hasErrors' => true, 'errors' => $this->errors))); + die(json_encode(array('hasErrors' => true, 'errors' => $this->errors))); } } } diff --git a/controllers/admin/AdminModulesController.php b/controllers/admin/AdminModulesController.php index 395bf377f..37a20c8be 100644 --- a/controllers/admin/AdminModulesController.php +++ b/controllers/admin/AdminModulesController.php @@ -218,7 +218,7 @@ class AdminModulesControllerCore extends AdminController public function displayAjaxRefreshModuleList() { - echo Tools::jsonEncode(array('status' => $this->status)); + echo json_encode(array('status' => $this->status)); } @@ -403,7 +403,7 @@ class AdminModulesControllerCore extends AdminController } } } else { - require_once(_PS_TOOL_DIR_.'tar/Archive_Tar.php'); + require_once _PS_TOOL_DIR_.'tar/Tar.php'; $archive = new Archive_Tar($file); if ($archive->extract($tmp_folder)) { $zip_folders = scandir($tmp_folder); @@ -1091,7 +1091,7 @@ class AdminModulesControllerCore extends AdminController // Get the list of installed module ans prepare it for ajax call. if (($list = Tools::getValue('installed_modules'))) { - Context::getContext()->smarty->assign('installed_modules', Tools::jsonEncode(explode('|', $list))); + Context::getContext()->smarty->assign('installed_modules', json_encode(explode('|', $list))); } // If redirect parameter is present and module already installed, we redirect on configuration module page @@ -1532,7 +1532,7 @@ class AdminModulesControllerCore extends AdminController } // AutoComplete array - $autocomplete_list .= Tools::jsonEncode(array( + $autocomplete_list .= json_encode(array( 'displayName' => (string)$module->displayName, 'desc' => (string)$module->description, 'name' => (string)$module->name, diff --git a/controllers/admin/AdminModulesPositionsController.php b/controllers/admin/AdminModulesPositionsController.php index be5266f61..cf6f52b82 100644 --- a/controllers/admin/AdminModulesPositionsController.php +++ b/controllers/admin/AdminModulesPositionsController.php @@ -552,7 +552,7 @@ class AdminModulesPositionsControllerCore extends AdminController } } $hookableList['hasError'] = false; - die(Tools::jsonEncode($hookableList)); + die(json_encode($hookableList)); } } @@ -582,7 +582,7 @@ class AdminModulesPositionsControllerCore extends AdminController } } } - die(Tools::jsonEncode($hookableModulesList)); + die(json_encode($hookableModulesList)); } } public function ajaxProcessSaveHook() diff --git a/controllers/admin/AdminOrdersController.php b/controllers/admin/AdminOrdersController.php index bac43229c..a4fc9c1a1 100644 --- a/controllers/admin/AdminOrdersController.php +++ b/controllers/admin/AdminOrdersController.php @@ -133,6 +133,7 @@ class AdminOrdersControllerCore extends AdminController 'align' => 'text-right', 'type' => 'price', 'currency' => true, + 'havingFilter' => true, 'callback' => 'setOrderCurrency', 'badge_success' => true, ), @@ -1548,7 +1549,7 @@ class AdminOrdersControllerCore extends AdminController $bookingOrderInfo = $objBookingDetail->getBookingDataByOrderId($order->id); // hotel booking statuses - $htlOrderStatus = HotelOrderStatus::getAllHotelOrderStatus(); + $htlOrderStatus = HotelBookingDetail::getAllHotelOrderStatus(); $this->tpl_view_vars = array( // refund info @@ -1715,7 +1716,7 @@ class AdminOrdersControllerCore extends AdminController $to_return = array('found' => false); } - $this->content = Tools::jsonEncode($to_return); + $this->content = json_encode($to_return); } public function ajaxProcessSendMailValidateOrder() @@ -1745,11 +1746,11 @@ class AdminOrdersControllerCore extends AdminController true, $cart->id_shop )) { - die(Tools::jsonEncode(array('errors' => false, 'result' => $this->l('The email was sent to your customer.')))); + die(json_encode(array('errors' => false, 'result' => $this->l('The email was sent to your customer.')))); } } } - $this->content = Tools::jsonEncode(array('errors' => true, 'result' => $this->l('Error in sending the email to your customer.'))); + $this->content = json_encode(array('errors' => true, 'result' => $this->l('Error in sending the email to your customer.'))); } } @@ -1759,7 +1760,7 @@ class AdminOrdersControllerCore extends AdminController $id_order = (int) Tools::getValue('id_order'); $order = new Order($id_order); if (!Validate::isLoadedObject($order)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('The order object cannot be loaded.') ))); @@ -1768,7 +1769,7 @@ class AdminOrdersControllerCore extends AdminController $old_cart_rules = Context::getContext()->cart->getCartRules(); if ($order->hasBeenShipped()) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('You cannot add products to delivered orders. ') ))); @@ -1782,37 +1783,37 @@ class AdminOrdersControllerCore extends AdminController $curr_date = date('Y-m-d'); /*Validations*/ if ($date_from == '') { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Please Enter Check In Date.'), ))); } elseif (!Validate::isDateFormat($date_from)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Please Enter a Valid Check In Date.'), ))); } elseif ($date_to == '') { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Please Enter Check Out Date.'), ))); } elseif (!Validate::isDateFormat($date_to)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Please Enter a valid Check out Date.'), ))); } elseif ($date_from < $curr_date) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Check In date should not be date before current date.'), ))); } elseif ($date_to <= $date_from) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Check out Date Should be after Check In date.'), ))); } elseif (!Validate::isUnsignedInt($product_informations['product_quantity'])) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Please Enter a valid Quantity.'), ))); @@ -1836,19 +1837,19 @@ class AdminOrdersControllerCore extends AdminController $total_available_rooms = $hotel_room_data['stats']['num_avail']; if ($total_available_rooms < $req_rm) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Required number of rooms are not available.'), ))); } } else { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Some error occured Please try again.'), ))); } } else { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Some error occured Please try again.'), ))); @@ -1865,7 +1866,7 @@ class AdminOrdersControllerCore extends AdminController $idProduct = $product_informations['product_id']; $product = new Product($idProduct, false, $order->id_lang); if (!Validate::isLoadedObject($product)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('The product object cannot be loaded.') ))); @@ -1874,7 +1875,7 @@ class AdminOrdersControllerCore extends AdminController if (isset($product_informations['product_attribute_id']) && $product_informations['product_attribute_id']) { $combination = new Combination($product_informations['product_attribute_id']); if (!Validate::isLoadedObject($combination)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('The combination object cannot be loaded.') ))); @@ -1986,9 +1987,9 @@ class AdminOrdersControllerCore extends AdminController if ($update_quantity < 0) { // If product has attribute, minimal quantity is set with minimal quantity of attribute $minimal_quantity = ($product_informations['product_attribute_id']) ? Attribute::getAttributeMinimalQty($product_informations['product_attribute_id']) : $product->minimal_quantity; - die(Tools::jsonEncode(array('error' => sprintf(Tools::displayError('You must add %d minimum quantity', false), $minimal_quantity)))); + die(json_encode(array('error' => sprintf(Tools::displayError('You must add %d minimum quantity', false), $minimal_quantity)))); } elseif (!$update_quantity) { - die(Tools::jsonEncode(array('error' => Tools::displayError('You already have the maximum quantity available for this product.', false)))); + die(json_encode(array('error' => Tools::displayError('You already have the maximum quantity available for this product.', false)))); } // If order is valid, we can create a new invoice or edit an existing invoice @@ -2264,7 +2265,7 @@ class AdminOrdersControllerCore extends AdminController } } - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => true, //'view' => $this->createTemplate('_product_line.tpl')->fetch(), 'can_edit' => $this->tabAccess['add'], @@ -2290,7 +2291,7 @@ class AdminOrdersControllerCore extends AdminController { // $order_detail = new OrderDetail(Tools::getValue('id_order_detail')); // if (!Validate::isLoadedObject($order_detail)) - // die(Tools::jsonEncode(array( + // die(json_encode(array( // 'result' => false, // 'error' => Tools::displayError('The OrderDetail object cannot be loaded.') // ))); @@ -2298,7 +2299,7 @@ class AdminOrdersControllerCore extends AdminController $id_product = Tools::getValue('id_product'); $product = new Product($id_product); if (!Validate::isLoadedObject($product)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('The product object cannot be loaded.') ))); @@ -2306,13 +2307,13 @@ class AdminOrdersControllerCore extends AdminController $address = new Address(Tools::getValue('id_address')); if (!Validate::isLoadedObject($address)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('The address object cannot be loaded.') ))); } - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => true, 'product' => $product, 'tax_rate' => $product->getTaxesRate($address), @@ -2354,47 +2355,47 @@ class AdminOrdersControllerCore extends AdminController $qty_diff = $product_quantity - $old_product_quantity; /*By webkul to validate fields before deleting the cart and order data form the tables*/ if ($id_hotel == '') { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Hotel Id is mising.'), ))); } elseif ($id_room == '') { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Room Id is missing.'), ))); } elseif ($new_date_from == '') { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Please Enter Check In Date.'), ))); } elseif (!Validate::isDateFormat($new_date_from)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Please Enter a Valid Check In Date.'), ))); } elseif ($new_date_to == '') { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Please Enter Check Out Date.'), ))); } elseif (!Validate::isDateFormat($new_date_to)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Please Enter a valid Check out Date.'), ))); } elseif ($new_date_from < $curr_date) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Check In date should not be after current date.'), ))); } elseif ($new_date_to <= $new_date_from) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Check out Date Should be after Check In date.'), ))); } elseif (!Validate::isUnsignedInt($product_quantity)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Invalid quantity.'), ))); @@ -2402,7 +2403,7 @@ class AdminOrdersControllerCore extends AdminController $rooms_booked = $obj_booking_detail->getRoomBookinInformationForDateRangeByOrder($id_room, $old_date_from, $old_date_to, $new_date_from, $new_date_to); if ($rooms_booked) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('This Room Unavailable For Selected Duration.'), ))); @@ -2580,7 +2581,7 @@ class AdminOrdersControllerCore extends AdminController )); if (!$res) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => $res, 'error' => Tools::displayError('An error occurred while editing the product line.') ))); @@ -2597,7 +2598,7 @@ class AdminOrdersControllerCore extends AdminController $this->sendChangedNotification($order); - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => $res, 'view' => $view, 'can_edit' => $this->tabAccess['add'], @@ -2627,32 +2628,32 @@ class AdminOrdersControllerCore extends AdminController $product_quantity = (int) $obj_booking_detail->getNumberOfDays($date_from, $date_to); /*By webkul to validate fields before deleting the cart and order data form the tables*/ if ($id_hotel == '') { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Hotel Id is mising.'), ))); } elseif ($id_room == '') { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Room Id is missing.'), ))); } elseif ($date_from == '') { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Check In Date is missing.'), ))); } elseif ($date_to == '') { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Check Out Date is missing.'), ))); } elseif ($date_to == '') { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Check Out Date is missing.'), ))); } elseif (!Validate::isUnsignedInt($product_quantity)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Invalid quantity.'), ))); @@ -2757,7 +2758,7 @@ class AdminOrdersControllerCore extends AdminController } if (!$res) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => $res, 'error' => Tools::displayError('An error occurred while attempting to delete the product line.') ))); @@ -2795,7 +2796,7 @@ class AdminOrdersControllerCore extends AdminController $this->sendChangedNotification($order); - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => $res, 'order' => $order, 'invoices' => $invoice_array, @@ -2807,28 +2808,28 @@ class AdminOrdersControllerCore extends AdminController protected function doEditProductValidation(OrderDetail $order_detail, Order $order, OrderInvoice $order_invoice = null) { if (!Validate::isLoadedObject($order_detail)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('The Order Detail object could not be loaded.') ))); } if (!empty($order_invoice) && !Validate::isLoadedObject($order_invoice)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('The invoice object cannot be loaded.') ))); } if (!Validate::isLoadedObject($order)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('The order object cannot be loaded.') ))); } if ($order_detail->id_order != $order->id) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('You cannot edit the order detail for this order.') ))); @@ -2836,14 +2837,14 @@ class AdminOrdersControllerCore extends AdminController // We can't edit a delivered order if ($order->hasBeenDelivered()) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('You cannot edit a delivered order.') ))); } if (!empty($order_invoice) && $order_invoice->id_order != Tools::getValue('id_order')) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('You cannot use this invoice for the order') ))); @@ -2854,21 +2855,21 @@ class AdminOrdersControllerCore extends AdminController $product_price_tax_excl = str_replace(',', '.', Tools::getValue('product_price_tax_excl')); if (!Validate::isPrice($product_price_tax_incl) || !Validate::isPrice($product_price_tax_excl)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Invalid price') ))); } //commented by webkul here quantity is gap between booking days which is calulated and validated in ajaxProcessEditProductOnOrder(); /*if (!is_array(Tools::getValue('product_quantity')) && !Validate::isUnsignedInt(Tools::getValue('product_quantity'))) - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Invalid quantity') ))); elseif (is_array(Tools::getValue('product_quantity'))) foreach (Tools::getValue('product_quantity') as $qty) if (!Validate::isUnsignedInt($qty)) - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('Invalid quantity') )));*/ @@ -2877,21 +2878,21 @@ class AdminOrdersControllerCore extends AdminController protected function doDeleteProductLineValidation(OrderDetail $order_detail, Order $order) { if (!Validate::isLoadedObject($order_detail)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('The Order Detail object could not be loaded.') ))); } if (!Validate::isLoadedObject($order)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('The order object cannot be loaded.') ))); } if ($order_detail->id_order != $order->id) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('You cannot delete the order detail.') ))); @@ -2899,7 +2900,7 @@ class AdminOrdersControllerCore extends AdminController // We can't edit a delivered order if ($order->hasBeenDelivered()) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('You cannot edit a delivered order.') ))); @@ -2916,13 +2917,13 @@ class AdminOrdersControllerCore extends AdminController $StockAvailable = StockAvailable::getQuantityAvailableByProduct($order_detail->product_id, $order_detail->product_attribute_id, $order_detail->id_shop); $product = new Product($order_detail->product_id, true, null, $order_detail->id_shop); if (!Validate::isLoadedObject($product)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('The Product object could not be loaded.') ))); } else { if (($StockAvailable < $add_quantity) && (!$product->isAvailableWhenOutOfStock((int)$product->out_of_stock))) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => false, 'error' => Tools::displayError('This product is no longer in stock with those attributes ') ))); @@ -3074,7 +3075,7 @@ class AdminOrdersControllerCore extends AdminController $authorized_modules = array(); if (!Validate::isLoadedObject($customer) || !is_array($modules)) { - die(Tools::jsonEncode(array('result' => false))); + die(json_encode(array('result' => false))); } foreach ($modules as $module) { @@ -3093,7 +3094,7 @@ class AdminOrdersControllerCore extends AdminController 'payment_modules' => $payment_modules, )); - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => true, 'view' => $this->createTemplate('_select_payment.tpl')->fetch(), ))); @@ -3128,7 +3129,7 @@ class AdminOrdersControllerCore extends AdminController $result['status'] = 'failed'; } - die(Tools::jsonEncode($result)); + die(json_encode($result)); } // To show rooms extra demands in the modal box in order details view page @@ -3238,8 +3239,8 @@ class AdminOrdersControllerCore extends AdminController if ($idCartBooking = Tools::getValue('id_cart_booking')) { if (Validate::isLoadedObject($objCartbookingCata = new HotelCartBookingData($idCartBooking))) { $roomDemands = Tools::getValue('room_demands'); - $roomDemands = Tools::jsonDecode($roomDemands, true); - $roomDemands = Tools::jsonEncode($roomDemands); + $roomDemands = json_decode($roomDemands, true); + $roomDemands = json_encode($roomDemands); $objCartbookingCata->extra_demands = $roomDemands; if ($objCartbookingCata->save()) { die('1'); @@ -3255,7 +3256,7 @@ class AdminOrdersControllerCore extends AdminController if ($idHtlBooking = Tools::getValue('id_htl_booking')) { if (Validate::isLoadedObject($objBookingDetail = new HotelBookingDetail($idHtlBooking))) { $roomDemands = Tools::getValue('room_demands'); - if ($roomDemands = Tools::jsonDecode($roomDemands, true)) { + if ($roomDemands = json_decode($roomDemands, true)) { $order = new Order($objBookingDetail->id_order); $vatAddress = new Address((int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $idLang = (int)$order->id_lang; @@ -3369,7 +3370,10 @@ class AdminOrdersControllerCore extends AdminController if (!$newStatus) { $this->errors[] = Tools::displayError('Invalid booking status found.'); - } elseif ($newStatus == 2 || $newStatus == 3) { + } elseif ( + $newStatus == HotelBookingDetail::STATUS_CHECKED_IN + || $newStatus == HotelBookingDetail::STATUS_CHECKED_OUT + ) { if (!$statusDate || !Validate::isDate($statusDate)) { $this->errors[] = Tools::displayError('Invalid dates found.'); } elseif ((strtotime($statusDate) < strtotime($dateFrom)) @@ -3381,24 +3385,24 @@ class AdminOrdersControllerCore extends AdminController if (!count($this->errors)) { $objBookingDetail = new HotelBookingDetail(); - if ($roomBookingInfo = $objBookingDetail->getRoomBookingData($idRoom, $idOrder)) { + if ($roomBookingInfo = $objBookingDetail->getRoomBookingData($idRoom, $idOrder, $dateFrom, $dateTo)) { // if admin choose Check-Out status - if ($newStatus == 3 + if ($newStatus == HotelBookingDetail::STATUS_CHECKED_OUT && $roomBookingInfo['check_in'] == '0000-00-00 00:00:00' ) { $this->errors[] = Tools::displayError('Room status must be set to Check-In before setting the room status to Check-Out.'); - } elseif ($newStatus == 3 + } elseif ($newStatus == HotelBookingDetail::STATUS_CHECKED_OUT && $roomBookingInfo['check_in'] != '0000-00-00 00:00:00' && strtotime($roomBookingInfo['check_in']) >= strtotime($statusDate) ) { $this->errors[] = Tools::displayError('Check-Out date can not be before Check-In date'). '('.date('d-m-Y', strtotime($roomBookingInfo['check_in'])).')'; - } elseif ($newStatus == 2 && $roomBookingInfo['check_out'] == '0000-00-00 00:00:00' + } elseif ($newStatus == HotelBookingDetail::STATUS_CHECKED_IN && $roomBookingInfo['check_out'] == '0000-00-00 00:00:00' && strtotime($roomBookingInfo['check_in']) >= strtotime($dateTo) ) { $this->errors[] = Tools::displayError('Check-In date can not be after Check-Out date'). '('.date('d-m-Y', strtotime($roomBookingInfo['date_to'])).')'; - } elseif ($newStatus == 2 && $roomBookingInfo['check_out'] != '0000-00-00 00:00:00' + } elseif ($newStatus == HotelBookingDetail::STATUS_CHECKED_IN && $roomBookingInfo['check_out'] != '0000-00-00 00:00:00' && strtotime($roomBookingInfo['check_out']) <= strtotime($statusDate) ) { $this->errors[] = Tools::displayError('Check-In date can not be after Check-Out date'). diff --git a/controllers/admin/AdminPerformanceController.php b/controllers/admin/AdminPerformanceController.php index 5f2e4f9b7..3e5976b34 100644 --- a/controllers/admin/AdminPerformanceController.php +++ b/controllers/admin/AdminPerformanceController.php @@ -1014,7 +1014,7 @@ class AdminPerformanceControllerCore extends AdminController $res = @memcache_get_server_status($memcache, $host, $port); } } - die(Tools::jsonEncode(array($res))); + die(json_encode(array($res))); } } die; diff --git a/controllers/admin/AdminProductsController.php b/controllers/admin/AdminProductsController.php index 35879aea7..de358ef20 100644 --- a/controllers/admin/AdminProductsController.php +++ b/controllers/admin/AdminProductsController.php @@ -600,7 +600,7 @@ class AdminProductsControllerCore extends AdminController public function ajaxProcessAddAttachment() { if ($this->tabAccess['edit'] === '0') { - return die(Tools::jsonEncode(array('error' => $this->l('You do not have the right permission')))); + return die(json_encode(array('error' => $this->l('You do not have the right permission')))); } if (isset($_FILES['attachment_file'])) { if ((int)$_FILES['attachment_file']['error'] === 1) { @@ -720,7 +720,7 @@ class AdminProductsControllerCore extends AdminController } } - die(Tools::jsonEncode($_FILES)); + die(json_encode($_FILES)); } } @@ -1296,7 +1296,7 @@ class AdminProductsControllerCore extends AdminController ); } - die(Tools::jsonEncode($json)); + die(json_encode($json)); } public function processSpecificPricePriorities() @@ -1632,7 +1632,7 @@ class AdminProductsControllerCore extends AdminController ); } - die(Tools::jsonEncode($json)); + die(json_encode($json)); } public function ajaxProcessDefaultProductAttribute() @@ -1656,7 +1656,7 @@ class AdminProductsControllerCore extends AdminController ); } - die(Tools::jsonEncode($json)); + die(json_encode($json)); } } @@ -1671,7 +1671,7 @@ class AdminProductsControllerCore extends AdminController $combinations[$key]['attributes'][] = array($combination['group_name'], $combination['attribute_name'], $combination['id_attribute']); } - die(Tools::jsonEncode($combinations)); + die(json_encode($combinations)); } } } @@ -1732,13 +1732,13 @@ class AdminProductsControllerCore extends AdminController public function ajaxProcessUpdateImagePosition() { if ($this->tabAccess['edit'] === '0') { - return die(Tools::jsonEncode(array('error' => $this->l('You do not have the right permission')))); + return die(json_encode(array('error' => $this->l('You do not have the right permission')))); } $res = false; if ($json = Tools::getValue('json')) { $res = true; $json = stripslashes($json); - $images = Tools::jsonDecode($json, true); + $images = json_decode($json, true); foreach ($images as $id => $position) { $img = new Image((int)$id); $img->position = (int)$position; @@ -1755,7 +1755,7 @@ class AdminProductsControllerCore extends AdminController public function ajaxProcessUpdateCover() { if ($this->tabAccess['edit'] === '0') { - return die(Tools::jsonEncode(array('error' => $this->l('You do not have the right permission')))); + return die(json_encode(array('error' => $this->l('You do not have the right permission')))); } Image::deleteCover((int)Tools::getValue('id_product')); $img = new Image((int)Tools::getValue('id_image')); @@ -2742,7 +2742,7 @@ class AdminProductsControllerCore extends AdminController if ($manufacturers) { foreach ($manufacturers as $manufacturer) { $tmp = array("optionValue" => $manufacturer['id_manufacturer'], "optionDisplay" => htmlspecialchars(trim($manufacturer['name']))); - $jsonArray[] = Tools::jsonEncode($tmp); + $jsonArray[] = json_encode($tmp); } } @@ -2925,7 +2925,9 @@ class AdminProductsControllerCore extends AdminController public function renderForm() { // This nice code (irony) is here to store the product name, because the row after will erase product name in multishop context - $this->product_name = $this->object->name[$this->context->language->id]; + if (Validate::isLoadedObject(($this->object))) { + $this->product_name = $this->object->name[$this->context->language->id]; + } if (!method_exists($this, 'initForm'.$this->tab_display)) { return; @@ -2965,7 +2967,7 @@ class AdminProductsControllerCore extends AdminController $this->tpl_form_vars['token'] = $this->token; $this->tpl_form_vars['combinationImagesJs'] = $this->getCombinationImagesJs(); $this->tpl_form_vars['PS_ALLOW_ACCENTED_CHARS_URL'] = (int)Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL'); - $this->tpl_form_vars['post_data'] = Tools::jsonEncode($_POST); + $this->tpl_form_vars['post_data'] = json_encode($_POST); $this->tpl_form_vars['save_error'] = !empty($this->errors); $this->tpl_form_vars['mod_evasive'] = Tools::apacheModExists('evasive'); $this->tpl_form_vars['mod_security'] = Tools::apacheModExists('security'); @@ -3339,7 +3341,7 @@ class AdminProductsControllerCore extends AdminController foreach ($hotelRoomInfo as &$room) { if ($room['id_status'] == 3) { $disabledDates = $objRoomDisableDates->getRoomDisableDates($room['id']); - $room['disabled_dates_json'] = Tools::jsonEncode($disabledDates); + $room['disabled_dates_json'] = json_encode($disabledDates); } } $data->assign('htl_room_info', $hotelRoomInfo); @@ -3492,7 +3494,7 @@ class AdminProductsControllerCore extends AdminController $disableDtsArr = array(); foreach ($room_status as $key => $status) { if ($status == 3) { - $disableDtsArr[$key] = Tools::jsonDecode($disable_dates[$key], true); + $disableDtsArr[$key] = json_decode($disable_dates[$key], true); $this->validateDisableDateRanges($disableDtsArr[$key]); } } @@ -3714,7 +3716,7 @@ class AdminProductsControllerCore extends AdminController } if ($booking_calendar_data) { - die(Tools::jsonEncode($booking_calendar_data)); + die(json_encode($booking_calendar_data)); } else { die(0); } @@ -4793,7 +4795,7 @@ class AdminProductsControllerCore extends AdminController } } - die(Tools::jsonEncode(array($image_uploader->getName() => $files))); + die(json_encode(array($image_uploader->getName() => $files))); } /** @@ -5421,28 +5423,28 @@ class AdminProductsControllerCore extends AdminController public function ajaxProcessProductQuantity() { if ($this->tabAccess['edit'] === '0') { - return die(Tools::jsonEncode(array('error' => $this->l('You do not have the right permission')))); + return die(json_encode(array('error' => $this->l('You do not have the right permission')))); } if (!Tools::getValue('actionQty')) { - return Tools::jsonEncode(array('error' => $this->l('Undefined action'))); + return json_encode(array('error' => $this->l('Undefined action'))); } $product = new Product((int)Tools::getValue('id_product'), true); switch (Tools::getValue('actionQty')) { case 'depends_on_stock': if (Tools::getValue('value') === false) { - die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); + die(json_encode(array('error' => $this->l('Undefined value')))); } if ((int)Tools::getValue('value') != 0 && (int)Tools::getValue('value') != 1) { - die(Tools::jsonEncode(array('error' => $this->l('Incorrect value')))); + die(json_encode(array('error' => $this->l('Incorrect value')))); } if (!$product->advanced_stock_management && (int)Tools::getValue('value') == 1) { - die(Tools::jsonEncode(array('error' => $this->l('Not possible if advanced stock management is disabled. ')))); + die(json_encode(array('error' => $this->l('Not possible if advanced stock management is disabled. ')))); } if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && (int)Tools::getValue('value') == 1 && (Pack::isPack($product->id) && !Pack::allUsesAdvancedStockManagement($product->id) && ($product->pack_stock_type == 2 || $product->pack_stock_type == 1 || ($product->pack_stock_type == 3 && (Configuration::get('PS_PACK_STOCK_TYPE') == 1 || Configuration::get('PS_PACK_STOCK_TYPE') == 2))))) { - die(Tools::jsonEncode(array('error' => $this->l('You cannot use advanced stock management for this pack because').'
'. + die(json_encode(array('error' => $this->l('You cannot use advanced stock management for this pack because').'
'. $this->l('- advanced stock management is not enabled for these room types').'
'. $this->l('- you have chosen to decrement room types quantities.')))); } @@ -5453,15 +5455,15 @@ class AdminProductsControllerCore extends AdminController case 'pack_stock_type': $value = Tools::getValue('value'); if ($value === false) { - die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); + die(json_encode(array('error' => $this->l('Undefined value')))); } if ((int)$value != 0 && (int)$value != 1 && (int)$value != 2 && (int)$value != 3) { - die(Tools::jsonEncode(array('error' => $this->l('Incorrect value')))); + die(json_encode(array('error' => $this->l('Incorrect value')))); } if ($product->depends_on_stock && !Pack::allUsesAdvancedStockManagement($product->id) && ((int)$value == 1 || (int)$value == 2 || ((int)$value == 3 && (Configuration::get('PS_PACK_STOCK_TYPE') == 1 || Configuration::get('PS_PACK_STOCK_TYPE') == 2)))) { - die(Tools::jsonEncode(array('error' => $this->l('You cannot use this stock management option because:').'
'. + die(json_encode(array('error' => $this->l('You cannot use this stock management option because:').'
'. $this->l('- advanced stock management is not enabled for these room types').'
'. $this->l('- advanced stock management is enabled for the pack')))); } @@ -5471,10 +5473,10 @@ class AdminProductsControllerCore extends AdminController case 'out_of_stock': if (Tools::getValue('value') === false) { - die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); + die(json_encode(array('error' => $this->l('Undefined value')))); } if (!in_array((int)Tools::getValue('value'), array(0, 1, 2))) { - die(Tools::jsonEncode(array('error' => $this->l('Incorrect value')))); + die(json_encode(array('error' => $this->l('Incorrect value')))); } StockAvailable::setProductOutOfStock($product->id, (int)Tools::getValue('value')); @@ -5482,10 +5484,10 @@ class AdminProductsControllerCore extends AdminController case 'set_qty': if (Tools::getValue('value') === false || (!is_numeric(trim(Tools::getValue('value'))))) { - die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); + die(json_encode(array('error' => $this->l('Undefined value')))); } if (Tools::getValue('id_product_attribute') === false) { - die(Tools::jsonEncode(array('error' => $this->l('Undefined id room type attribute')))); + die(json_encode(array('error' => $this->l('Undefined id room type attribute')))); } StockAvailable::setQuantity($product->id, (int)Tools::getValue('id_product_attribute'), (int)Tools::getValue('value')); @@ -5495,18 +5497,18 @@ class AdminProductsControllerCore extends AdminController $error = ob_get_contents(); if (!empty($error)) { ob_end_clean(); - die(Tools::jsonEncode(array('error' => $error))); + die(json_encode(array('error' => $error))); } break; case 'advanced_stock_management' : if (Tools::getValue('value') === false) { - die(Tools::jsonEncode(array('error' => $this->l('Undefined value')))); + die(json_encode(array('error' => $this->l('Undefined value')))); } if ((int)Tools::getValue('value') != 1 && (int)Tools::getValue('value') != 0) { - die(Tools::jsonEncode(array('error' => $this->l('Incorrect value')))); + die(json_encode(array('error' => $this->l('Incorrect value')))); } if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && (int)Tools::getValue('value') == 1) { - die(Tools::jsonEncode(array('error' => $this->l('Not possible if advanced stock management is disabled. ')))); + die(json_encode(array('error' => $this->l('Not possible if advanced stock management is disabled. ')))); } $product->setAdvancedStockManagement((int)Tools::getValue('value')); @@ -5516,7 +5518,7 @@ class AdminProductsControllerCore extends AdminController break; } - die(Tools::jsonEncode(array('error' => false))); + die(json_encode(array('error' => false))); } public function getCombinationImagesJS() @@ -5666,7 +5668,7 @@ class AdminProductsControllerCore extends AdminController GROUP BY pl.`id_product` LIMIT '.(int)$limit); } - die(Tools::jsonEncode($result)); + die(json_encode($result)); } } diff --git a/controllers/admin/AdminQuickAccessesController.php b/controllers/admin/AdminQuickAccessesController.php index 450a1579b..38923e60d 100644 --- a/controllers/admin/AdminQuickAccessesController.php +++ b/controllers/admin/AdminQuickAccessesController.php @@ -153,7 +153,7 @@ class AdminQuickAccessesControllerCore extends AdminController public function getQuickAccessesList() { $links = QuickAccess::getQuickAccesses($this->context->language->id); - return Tools::jsonEncode(array_map(array($this, 'getLinkToken'), $links)); + return json_encode(array_map(array($this, 'getLinkToken'), $links)); } public function getLinkToken($item) @@ -195,7 +195,7 @@ class AdminQuickAccessesControllerCore extends AdminController $this->errors = array_unique($this->errors); if (!empty($this->errors)) { $this->errors['has_errors'] = true; - $this->ajaxDie(Tools::jsonEncode($this->errors)); + $this->ajaxDie(json_encode($this->errors)); return false; } return $this->getQuickAccessesList(); diff --git a/controllers/admin/AdminRequestSqlController.php b/controllers/admin/AdminRequestSqlController.php index 121bdcf5f..a8e5507b1 100644 --- a/controllers/admin/AdminRequestSqlController.php +++ b/controllers/admin/AdminRequestSqlController.php @@ -197,7 +197,7 @@ class AdminRequestSqlControllerCore extends AdminController unset($attributes[$key]['Default']); unset($attributes[$key]['Extra']); } - die(Tools::jsonEncode($attributes)); + die(json_encode($attributes)); } } diff --git a/controllers/admin/AdminSearchController.php b/controllers/admin/AdminSearchController.php index af5b89e8a..b8dc233dc 100644 --- a/controllers/admin/AdminSearchController.php +++ b/controllers/admin/AdminSearchController.php @@ -191,7 +191,7 @@ class AdminSearchControllerCore extends AdminController $iso_lang = Tools::strtolower(Context::getContext()->language->iso_code); $iso_country = Tools::strtolower(Country::getIsoById(Configuration::get('PS_COUNTRY_DEFAULT'))); if (($json_content = Tools::file_get_contents('https://api-addons.prestashop.com/'._PS_VERSION_.'/search/'.urlencode($this->query).'/'.$iso_country.'/'.$iso_lang.'/')) != false) { - $results = Tools::jsonDecode($json_content, true); + $results = json_decode($json_content, true); if (isset($results['id'])) { $this->_list['addons'] = array($results); } else { diff --git a/controllers/admin/AdminShopController.php b/controllers/admin/AdminShopController.php index a8624c117..e02368fa6 100644 --- a/controllers/admin/AdminShopController.php +++ b/controllers/admin/AdminShopController.php @@ -36,7 +36,7 @@ class AdminShopControllerCore extends AdminController $this->table = 'shop'; $this->className = 'Shop'; $this->multishop_context = Shop::CONTEXT_ALL; - + $this->id_shop_group = (int)Tools::getValue('id_shop_group'); /* if $_GET['id_shop'] is transmitted, virtual url can be loaded in config.php, so we wether transmit shop_id in herfs */ @@ -250,7 +250,7 @@ class AdminShopControllerCore extends AdminController elseif (Shop::getTotalShops() == 1) $this->errors[] = Tools::displayError('You cannot disable the last shop.'); }*/ - + if (Tools::isSubmit('submitAddshopAndStay') || Tools::isSubmit('submitAddshop')) { $shop_group = new ShopGroup((int)Tools::getValue('id_shop_group')); if ($shop_group->shopNameExists(Tools::getValue('name'), (int)Tools::getValue('id_shop'))) { @@ -475,7 +475,7 @@ class AdminShopControllerCore extends AdminController $root_category = new Category($root_categories[0]['id_category']); $children = $root_category->getAllChildren($this->context->language->id); $selected_cat[] = $root_categories[0]['id_category']; - + foreach ($children as $child) { $selected_cat[] = $child->id; } @@ -576,7 +576,7 @@ class AdminShopControllerCore extends AdminController 'zone' => $this->l('Zones'), 'cart_rule' => $this->l('Cart rules'), ); - + // Hook for duplication of shop data $modules_list = Hook::getHookModuleExecList('actionShopDataDuplication'); if (is_array($modules_list) && count($modules_list) > 0) { @@ -586,7 +586,7 @@ class AdminShopControllerCore extends AdminController } asort($import_data); - + if (!$this->object->id) { $this->fields_import_form = array( 'radio' => array( @@ -615,9 +615,9 @@ class AdminShopControllerCore extends AdminController $this->fields_value = array( 'id_shop_group' => (Tools::getValue('id_shop_group') ? Tools::getValue('id_shop_group') : - (isset($obj->id_shop_group)) ? $obj->id_shop_group : Shop::getContextShopGroupID()), + ((isset($obj->id_shop_group)) ? $obj->id_shop_group : Shop::getContextShopGroupID())), 'id_category' => (Tools::getValue('id_category') ? Tools::getValue('id_category') : - (isset($obj->id_category)) ? $obj->id_category : (int)Configuration::get('PS_HOME_CATEGORY')), + ((isset($obj->id_category)) ? $obj->id_category : (int)Configuration::get('PS_HOME_CATEGORY'))), 'id_theme_checked' => (isset($obj->id_theme) ? $obj->id_theme : $id_theme) ); @@ -653,7 +653,7 @@ class AdminShopControllerCore extends AdminController if (Tools::isSubmit('id_category_default')) { $_POST['id_category'] = (int)Tools::getValue('id_category_default'); } - + /* Checking fields validity */ $this->validateRules(); @@ -711,13 +711,13 @@ class AdminShopControllerCore extends AdminController if (!array_key_exists('Edit', self::$cache_lang)) { self::$cache_lang['Edit'] = $this->l('Edit', 'Helper'); } - + $tpl->assign(array( 'href' => $this->context->link->getAdminLink('AdminShop').'&shop_id='.(int)$id.'&update'.$this->table, 'action' => self::$cache_lang['Edit'], 'id' => $id )); - + return $tpl->fetch(); } else { return; @@ -738,7 +738,7 @@ class AdminShopControllerCore extends AdminController $root_category = new Category($root_categories[0]['id_category']); $children = $root_category->getAllChildren($this->context->language->id); $selected_cat[] = $root_categories[0]['id_category']; - + foreach ($children as $child) { $selected_cat[] = $child->id; } @@ -860,6 +860,6 @@ class AdminShopControllerCore extends AdminController 'children' => $tree, )); - die(Tools::jsonEncode($tree)); + die(json_encode($tree)); } } diff --git a/controllers/admin/AdminShopUrlController.php b/controllers/admin/AdminShopUrlController.php index d3e334c9d..f0e9f20ae 100644 --- a/controllers/admin/AdminShopUrlController.php +++ b/controllers/admin/AdminShopUrlController.php @@ -281,7 +281,7 @@ class AdminShopUrlControllerCore extends AdminController } $this->tpl_form_vars = array( - 'js_shop_url' => Tools::jsonEncode($list_shop_with_url) + 'js_shop_url' => json_encode($list_shop_with_url) ); $this->fields_value = array( diff --git a/controllers/admin/AdminStatsController.php b/controllers/admin/AdminStatsController.php index 2d53728dc..8494928a5 100644 --- a/controllers/admin/AdminStatsController.php +++ b/controllers/admin/AdminStatsController.php @@ -542,7 +542,7 @@ class AdminStatsControllerCore extends AdminStatsTabController } $value .= '%'; - // ConfigurationKPI::updateValue('CONVERSION_RATE_CHART', Tools::jsonEncode($data)); + // ConfigurationKPI::updateValue('CONVERSION_RATE_CHART', json_encode($data)); ConfigurationKPI::updateValue('CONVERSION_RATE', $value); ConfigurationKPI::updateValue('CONVERSION_RATE_EXPIRE', strtotime(date('Y-m-d 00:00:00', strtotime('+1 day')))); break; @@ -793,8 +793,8 @@ class AdminStatsControllerCore extends AdminStatsTabController if (isset($data)) { $array['data'] = $data; } - die(Tools::jsonEncode($array)); + die(json_encode($array)); } - die(Tools::jsonEncode(array('has_errors' => true))); + die(json_encode(array('has_errors' => true))); } } diff --git a/controllers/admin/AdminStatsTabController.php b/controllers/admin/AdminStatsTabController.php index c8e7e38eb..54b1682fb 100644 --- a/controllers/admin/AdminStatsTabController.php +++ b/controllers/admin/AdminStatsTabController.php @@ -51,7 +51,7 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor } $this->content .= $this->renderView(); } - + $this->content .= $this->displayMenu(); $this->content .= $this->displayCalendar(); $this->content .= $this->displayStats(); @@ -97,7 +97,7 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor $identifier = 'module'; $id = Tools::getValue('module'); } - + $action = Context::getContext()->link->getAdminLink('AdminStats'); $action .= ($action && $table ? '&'.Tools::safeOutput($action) : ''); $action .= ($identifier && $id ? '&'.Tools::safeOutput($identifier).'='.(int)$id : ''); @@ -172,7 +172,7 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor return $tpl->fetch(); } - + public function checkModulesNames($a, $b) { return (bool)($a['displayName'] > $b['displayName']); @@ -205,7 +205,7 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor if (!isset($module_instance)) { $module_instance = Module::getInstanceByName($module_name); } - + if ($module_instance && $module_instance->active) { $hook = Hook::exec('displayAdminStatsModules', null, $module_instance->id); } @@ -223,9 +223,9 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor public function postProcess() { $this->context = Context::getContext(); - + $this->processDateRange(); - + if (Tools::getValue('submitSettings')) { if ($this->tabAccess['edit'] === '1') { self::$currentIndex .= '&module='.Tools::getValue('module'); @@ -237,7 +237,7 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor } } } - + public function processDateRange() { if (Tools::isSubmit('submitDatePicker')) { @@ -281,21 +281,21 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor } } } - + public function ajaxProcessSetDashboardDateRange() { $this->processDateRange(); - + if ($this->isXmlHttpRequest()) { if (is_array($this->errors) && count($this->errors)) { - die(Tools::jsonEncode(array( + die(json_encode(array( 'has_errors' => true, 'errors' => array($this->errors), 'date_from' => $this->context->employee->stats_date_from, 'date_to' => $this->context->employee->stats_date_to) )); } else { - die(Tools::jsonEncode(array( + die(json_encode(array( 'has_errors' => false, 'date_from' => $this->context->employee->stats_date_from, 'date_to' => $this->context->employee->stats_date_to) diff --git a/controllers/admin/AdminSupplyOrdersController.php b/controllers/admin/AdminSupplyOrdersController.php index cdae27c2a..485bf6d90 100644 --- a/controllers/admin/AdminSupplyOrdersController.php +++ b/controllers/admin/AdminSupplyOrdersController.php @@ -719,7 +719,7 @@ class AdminSupplyOrdersControllerCore extends AdminController } $this->tpl_form_vars['products_list'] = $products; - $this->tpl_form_vars['product_ids'] = implode($product_ids, '|'); + $this->tpl_form_vars['product_ids'] = implode('|', $product_ids); $this->tpl_form_vars['product_ids_to_delete'] = ''; $this->tpl_form_vars['supplier_id'] = $supply_order->id_supplier; $this->tpl_form_vars['currency'] = $currency; @@ -1771,7 +1771,7 @@ class AdminSupplyOrdersControllerCore extends AdminController } } if ($items) { - die(Tools::jsonEncode($items)); + die(json_encode($items)); } die(1); diff --git a/controllers/admin/AdminTaxRulesGroupController.php b/controllers/admin/AdminTaxRulesGroupController.php index 3c54318ca..ba62da512 100644 --- a/controllers/admin/AdminTaxRulesGroupController.php +++ b/controllers/admin/AdminTaxRulesGroupController.php @@ -546,7 +546,7 @@ class AdminTaxRulesGroupControllerCore extends AdminController foreach ($tax_rules as $key => $result) { $output[$key] = $result; } - die(Tools::jsonEncode($output)); + die(json_encode($output)); } } diff --git a/controllers/admin/AdminTranslationsController.php b/controllers/admin/AdminTranslationsController.php index 87a586dcb..d2024c057 100644 --- a/controllers/admin/AdminTranslationsController.php +++ b/controllers/admin/AdminTranslationsController.php @@ -179,8 +179,8 @@ class AdminTranslationsControllerCore extends AdminController $file_name = $this->link_lang_pack.'?version='._PS_VERSION_; $array_stream_context = @stream_context_create(array('http' => array('method' => 'GET', 'timeout' => 8))); if ($lang_packs = Tools::file_get_contents($file_name, false, $array_stream_context)) { - // Notice : for php < 5.2 compatibility, Tools::jsonDecode. The second parameter to true will set us - if ($lang_packs != '' && $lang_packs = Tools::jsonDecode($lang_packs, true)) { + // Notice : for php < 5.2 compatibility, json_decode. The second parameter to true will set us + if ($lang_packs != '' && $lang_packs = json_decode($lang_packs, true)) { foreach ($lang_packs as $key => $lang_pack) { if (!Language::isInstalled($lang_pack['iso_code'])) { $packs_to_install[$key] = $lang_pack; @@ -481,7 +481,7 @@ class AdminTranslationsControllerCore extends AdminController $this->exportTabs(); $items = array_flip(Language::getFilesList($this->lang_selected->iso_code, $this->theme_selected, false, false, false, false, true)); $file_name = _PS_TRANSLATIONS_DIR_.'/export/'.$this->lang_selected->iso_code.'.gzip'; - require_once(_PS_TOOL_DIR_.'tar/Archive_Tar.php'); + require_once(_PS_TOOL_DIR_.'tar/Tar.php'); $gz = new Archive_Tar($file_name, true); if ($gz->createModify($items, null, _PS_ROOT_DIR_)) { ob_start(); @@ -718,7 +718,7 @@ class AdminTranslationsControllerCore extends AdminController if (!isset($_FILES['file']['tmp_name']) || !$_FILES['file']['tmp_name']) { $this->errors[] = Tools::displayError('No file has been selected.'); } else { - require_once(_PS_TOOL_DIR_.'tar/Archive_Tar.php'); + require_once(_PS_TOOL_DIR_.'tar/Tar.php'); $gz = new Archive_Tar($_FILES['file']['tmp_name'], true); $filename = $_FILES['file']['name']; $iso_code = str_replace(array('.tar.gz', '.gzip'), '', $filename); @@ -859,7 +859,7 @@ class AdminTranslationsControllerCore extends AdminController if ($content) { $file = _PS_TRANSLATIONS_DIR_.$arr_import_lang[0].'.gzip'; if ((bool)@file_put_contents($file, $content)) { - require_once(_PS_TOOL_DIR_.'/tar/Archive_Tar.php'); + require_once(_PS_TOOL_DIR_.'/tar/Tar.php'); $gz = new Archive_Tar($file, true); if (_PS_MODE_DEV_) { $gz->setErrorHandling(PEAR_ERROR_TRIGGER, E_USER_WARNING); @@ -1019,7 +1019,7 @@ class AdminTranslationsControllerCore extends AdminController $arr_good_ext = array('.tpl', '.php'); foreach ($files as $key => $file) { - if ($file{0} === '.' || in_array(substr($file, 0, strrpos($file, '.')), $this->all_iso_lang)) { + if ($file[0] === '.' || in_array(substr($file, 0, strrpos($file, '.')), $this->all_iso_lang)) { unset($files[$key]); } elseif ($type_clear === 'file' && !in_array(substr($file, strrpos($file, '.')), $arr_good_ext)) { unset($files[$key]); @@ -2872,7 +2872,7 @@ class AdminTranslationsControllerCore extends AdminController $initial_root_dir = $root_dir; foreach ($modules as $module) { $root_dir = $initial_root_dir; - if ($module{0} == '.') { + if ($module[0] == '.') { continue; } diff --git a/controllers/front/AddressController.php b/controllers/front/AddressController.php index 2606da4ab..a03befc81 100644 --- a/controllers/front/AddressController.php +++ b/controllers/front/AddressController.php @@ -204,7 +204,7 @@ class AddressControllerCore extends FrontController 'hasError' => (bool)$this->errors, 'errors' => $this->errors ); - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); } } @@ -231,7 +231,7 @@ class AddressControllerCore extends FrontController 'id_address_delivery' => (int)$this->context->cart->id_address_delivery, 'id_address_invoice' => (int)$this->context->cart->id_address_invoice ); - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); } // Redirect to old page or current page @@ -364,7 +364,7 @@ class AddressControllerCore extends FrontController 'hasError' => !empty($this->errors), 'errors' => $this->errors ); - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); } } } diff --git a/controllers/front/AuthController.php b/controllers/front/AuthController.php index 686694ef8..b1b374b2b 100644 --- a/controllers/front/AuthController.php +++ b/controllers/front/AuthController.php @@ -168,7 +168,7 @@ class AuthControllerCore extends FrontController 'page' => $this->context->smarty->fetch($this->template), 'token' => Tools::getToken(false) ); - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); } } @@ -349,7 +349,7 @@ class AuthControllerCore extends FrontController 'errors' => $this->errors, 'token' => Tools::getToken(false) ); - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); } else { $this->context->smarty->assign('authentification_error', $this->errors); } @@ -516,7 +516,7 @@ class AuthControllerCore extends FrontController 'id_address_invoice' => $this->context->cart->id_address_invoice, 'token' => Tools::getToken(false) ); - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); } if (($back = Tools::getValue('back')) && $back == Tools::secureReferrer($back)) { @@ -690,7 +690,7 @@ class AuthControllerCore extends FrontController 'id_address_invoice' => $this->context->cart->id_address_invoice, 'token' => Tools::getToken(false) ); - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); } // if registration type is in two steps, we redirect to register address if (!Configuration::get('PS_REGISTRATION_PROCESS_TYPE') && !$this->ajax && !Tools::isSubmit('submitGuestAccount')) { @@ -730,7 +730,7 @@ class AuthControllerCore extends FrontController 'isSaved' => false, 'id_customer' => 0 ); - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); } $this->context->smarty->assign('account_error', $this->errors); } diff --git a/controllers/front/CartController.php b/controllers/front/CartController.php index 842629439..4ee5f81cd 100644 --- a/controllers/front/CartController.php +++ b/controllers/front/CartController.php @@ -105,7 +105,7 @@ class CartControllerCore extends FrontController } } elseif (!$this->isTokenValid()) { if (Tools::getValue('ajax')) { - $this->ajaxDie(Tools::jsonEncode(array( + $this->ajaxDie(json_encode(array( 'hasError' => true, 'errors' => array(Tools::displayError('Impossible to add the product to the cart. Please refresh page.')), ))); @@ -137,7 +137,7 @@ class CartControllerCore extends FrontController } if ($total_quantity < $minimal_quantity) { - $this->ajaxDie(Tools::jsonEncode(array( + $this->ajaxDie(json_encode(array( 'hasError' => true, 'errors' => array(sprintf(Tools::displayError('You must add %d minimum quantity', !Tools::getValue('ajax')), $minimal_quantity)), ))); @@ -210,7 +210,7 @@ class CartControllerCore extends FrontController $new_id_address_delivery = (int)Tools::getValue('new_id_address_delivery'); if (!count(Carrier::getAvailableCarrierList(new Product($this->id_product), null, $new_id_address_delivery))) { - $this->ajaxDie(Tools::jsonEncode(array( + $this->ajaxDie(json_encode(array( 'hasErrors' => true, 'error' => Tools::displayError('It is not possible to deliver this product to the selected address.', false), ))); @@ -312,7 +312,7 @@ class CartControllerCore extends FrontController if (isset($hotel_room_data['stats']['num_avail'])) { $total_available_rooms = $hotel_room_data['stats']['num_avail']; if ($total_available_rooms < $req_rm) { - die(Tools::jsonEncode(array('status' => 'unavailable_quantity', 'avail_rooms' => $total_available_rooms))); + die(json_encode(array('status' => 'unavailable_quantity', 'avail_rooms' => $total_available_rooms))); } } else { $this->errors[] = Tools::displayError('Rooms are unavailable. Please try with different dates'); @@ -322,10 +322,10 @@ class CartControllerCore extends FrontController } } } else { - die(Tools::jsonEncode(array('status' => 'failed3'))); + die(json_encode(array('status' => 'failed3'))); } } else { - die(Tools::jsonEncode(array('status' => 'failed4'))); + die(json_encode(array('status' => 'failed4'))); } } @@ -416,8 +416,8 @@ class CartControllerCore extends FrontController foreach ($hotel_room_info_arr as $key_hotel_room_info => $val_hotel_room_info) { if ($chkQty < $req_rm) { $roomDemand = Tools::getValue('roomDemands'); - $roomDemand = Tools::jsonDecode($roomDemand, true); - $roomDemand = Tools::jsonEncode($roomDemand); + $roomDemand = json_decode($roomDemand, true); + $roomDemand = json_encode($roomDemand); $obj_htl_cart_booking_data = new HotelCartBookingData(); $obj_htl_cart_booking_data->id_cart = $this->context->cart->id; $obj_htl_cart_booking_data->id_guest = $this->context->cart->id_guest; @@ -519,10 +519,10 @@ class CartControllerCore extends FrontController public function displayAjax() { if ($this->errors) { - $this->ajaxDie(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors))); + $this->ajaxDie(json_encode(array('hasError' => true, 'errors' => $this->errors))); } if ($this->ajax_refresh) { - $this->ajaxDie(Tools::jsonEncode(array('refresh' => true))); + $this->ajaxDie(json_encode(array('refresh' => true))); } // write cookie if can't on destruct @@ -560,7 +560,7 @@ class CartControllerCore extends FrontController $json = ''; Hook::exec('actionCartListOverride', array('summary' => $result, 'json' => &$json)); - $this->ajaxDie(Tools::jsonEncode(array_merge($result, (array)Tools::jsonDecode($json, true)))); + $this->ajaxDie(json_encode(array_merge($result, (array)json_decode($json, true)))); } // @todo create a hook elseif (file_exists(_PS_MODULE_DIR_.'/blockcart/blockcart-ajax.php')) { diff --git a/controllers/front/ContactController.php b/controllers/front/ContactController.php index 526fc6aee..54c5dbe17 100644 --- a/controllers/front/ContactController.php +++ b/controllers/front/ContactController.php @@ -305,7 +305,7 @@ class ContactControllerCore extends FrontController if (Configuration::get('WK_GOOGLE_ACTIVE_MAP')) { $hotelLocationArray = $objHotelInfo->getMapFormatHotelsInfo(Configuration::get('WK_MAP_HOTEL_ACTIVE_ONLY')); if ($hotelLocationArray) { - $this->context->smarty->assign('hotelLocationArray', Tools::jsonEncode($hotelLocationArray)); + $this->context->smarty->assign('hotelLocationArray', json_encode($hotelLocationArray)); } } //End diff --git a/controllers/front/OrderController.php b/controllers/front/OrderController.php index 340d534d9..a0b19b57d 100644 --- a/controllers/front/OrderController.php +++ b/controllers/front/OrderController.php @@ -138,7 +138,7 @@ class OrderControllerCore extends ParentOrderController ) ) ); - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); } if ($this->nbProducts) { diff --git a/controllers/front/OrderDetailController.php b/controllers/front/OrderDetailController.php index cde394877..19c3a1def 100644 --- a/controllers/front/OrderDetailController.php +++ b/controllers/front/OrderDetailController.php @@ -208,7 +208,7 @@ class OrderDetailControllerCore extends FrontController $hasError = 1; } if ($bookingRefunds = Tools::getValue('bookings_to_refund')) { - if (!count($bookingRefunds = Tools::jsonDecode($bookingRefunds, true))) { + if (!count($bookingRefunds = json_decode($bookingRefunds, true))) { $hasError = 1; } else { foreach ($bookingRefunds as $idHtlBooking) { @@ -248,9 +248,9 @@ class OrderDetailControllerCore extends FrontController // Emails to customer, admin on refund request state change $objOrderReturn->changeIdOrderReturnState(OrderReturnState::ORDER_RETRUN_FIRST_STATUS, $objOrderReturn->id); - die(Tools::jsonEncode(array('status' => 1))); + die(json_encode(array('status' => 1))); } - die(Tools::jsonEncode(array('status' => 0))); + die(json_encode(array('status' => 0))); } // END ajax request handle diff --git a/controllers/front/OrderOpcController.php b/controllers/front/OrderOpcController.php index bb7730527..1c0227326 100644 --- a/controllers/front/OrderOpcController.php +++ b/controllers/front/OrderOpcController.php @@ -75,7 +75,7 @@ class OrderOpcControllerCore extends ParentOrderController $this->getFormatedSummaryDetail() ); Cart::addExtraCarriers($return); - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); } else { $this->errors[] = Tools::displayError('An error occurred while updating the cart.'); } @@ -89,7 +89,7 @@ class OrderOpcControllerCore extends ParentOrderController case 'updateTOSStatusAndGetPayments': if (Tools::isSubmit('checked')) { $this->context->cookie->checkedTOS = (int)Tools::getValue('checked'); - $this->ajaxDie(Tools::jsonEncode(array( + $this->ajaxDie(json_encode(array( 'HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods() ))); @@ -97,7 +97,7 @@ class OrderOpcControllerCore extends ParentOrderController break; case 'getCarrierList': - $this->ajaxDie(Tools::jsonEncode($this->_getCarrierList())); + $this->ajaxDie(json_encode($this->_getCarrierList())); break; case 'editCustomer': @@ -132,14 +132,14 @@ class OrderOpcControllerCore extends ParentOrderController } else { $return['isSaved'] = false; } - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); break; case 'getAddressBlockAndCarriersAndPayments': if ($this->context->customer->isLogged() || $this->context->customer->isGuest()) { // check if customer have addresses if (!Customer::getAddressesTotalById($this->context->customer->id)) { - $this->ajaxDie(Tools::jsonEncode(array('no_address' => 1))); + $this->ajaxDie(json_encode(array('no_address' => 1))); } if (file_exists(_PS_MODULE_DIR_.'blockuserinfo/blockuserinfo.php')) { include_once(_PS_MODULE_DIR_.'blockuserinfo/blockuserinfo.php'); @@ -183,7 +183,7 @@ class OrderOpcControllerCore extends ParentOrderController ), $this->getFormatedSummaryDetail() ); - $this->ajaxDie(Tools::jsonEncode($return)); + $this->ajaxDie(json_encode($return)); } die(Tools::displayError()); break; @@ -265,11 +265,11 @@ class OrderOpcControllerCore extends ParentOrderController 'refresh' => (bool)$this->ajax_refresh), $this->getFormatedSummaryDetail() ); - $this->ajaxDie(Tools::jsonEncode($result)); + $this->ajaxDie(json_encode($result)); } } if (count($this->errors)) { - $this->ajaxDie(Tools::jsonEncode(array( + $this->ajaxDie(json_encode(array( 'hasError' => true, 'errors' => $this->errors ))); @@ -958,8 +958,8 @@ class OrderOpcControllerCore extends ParentOrderController if ($idCartBooking = Tools::getValue('id_cart_booking')) { if (Validate::isLoadedObject($objCartbookingCata = new HotelCartBookingData($idCartBooking))) { $roomDemands = Tools::getValue('room_demands'); - $roomDemands = Tools::jsonDecode($roomDemands, true); - $roomDemands = Tools::jsonEncode($roomDemands); + $roomDemands = json_decode($roomDemands, true); + $roomDemands = json_encode($roomDemands); $objCartbookingCata->extra_demands = $roomDemands; if ($objCartbookingCata->save()) { die('1'); diff --git a/controllers/front/ProductController.php b/controllers/front/ProductController.php index 46cfd89d0..cafe51955 100644 --- a/controllers/front/ProductController.php +++ b/controllers/front/ProductController.php @@ -969,7 +969,7 @@ class ProductControllerCore extends FrontController $totalPrice += $totalRoomPrice; $demandsPrice = 0; if ($roomDemand = Tools::getValue('room_demands')) { - if ($roomDemand = Tools::jsonDecode($roomDemand, true)) { + if ($roomDemand = json_decode($roomDemand, true)) { $objRoomDemandPrice = new HotelRoomTypeDemandPrice(); $demandsPrice = $objRoomDemandPrice->getRoomTypeDemandsTotalPrice( $idProduct, @@ -1009,6 +1009,6 @@ class ProductControllerCore extends FrontController $result['msg'] = 'failed3'; $result['avail_rooms'] = 0; } - die(Tools::jsonEncode($result)); + die(json_encode($result)); } } diff --git a/controllers/front/SearchController.php b/controllers/front/SearchController.php index 7e36fc1a3..ebe5d78a5 100644 --- a/controllers/front/SearchController.php +++ b/controllers/front/SearchController.php @@ -64,12 +64,12 @@ class SearchControllerCore extends FrontController } Hook::exec('actionSearch', array('expr' => $query, 'total' => count($searchResults))); } - $this->ajaxDie(Tools::jsonEncode($searchResults)); + $this->ajaxDie(json_encode($searchResults)); } //Only controller content initialization when the user use the normal search parent::initContent(); - + $product_per_page = isset($this->context->cookie->nb_item_per_page) ? (int)$this->context->cookie->nb_item_per_page : Configuration::get('PS_PRODUCTS_PER_PAGE'); if ($this->instant_search && !is_array($query)) { diff --git a/install/classes/controllerHttp.php b/install/classes/controllerHttp.php index de96a6a60..caceb3a16 100644 --- a/install/classes/controllerHttp.php +++ b/install/classes/controllerHttp.php @@ -430,7 +430,7 @@ abstract class InstallControllerHttp if (!$success && empty($message)) { $message = print_r(@error_get_last(), true); } - die(Tools::jsonEncode(array( + die(json_encode(array( 'success' => (bool)$success, 'message' => $message, // 'memory' => round(memory_get_peak_usage()/1024/1024, 2).' Mo', diff --git a/install/controllers/console/process.php b/install/controllers/console/process.php index fa56b6bec..afeadfe82 100644 --- a/install/controllers/console/process.php +++ b/install/controllers/console/process.php @@ -221,7 +221,7 @@ class InstallControllerConsoleProcess extends InstallControllerConsole $this->model_install->xml_loader_ids = $this->datas->xml_loader_ids; $result = $this->model_install->populateDatabase(); $this->datas->xml_loader_ids = $this->model_install->xml_loader_ids; - Configuration::updateValue('PS_INSTALL_XML_LOADERS_ID', Tools::jsonEncode($this->datas->xml_loader_ids)); + Configuration::updateValue('PS_INSTALL_XML_LOADERS_ID', json_encode($this->datas->xml_loader_ids)); return $result; } @@ -269,7 +269,7 @@ class InstallControllerConsoleProcess extends InstallControllerConsole { $this->initializeContext(); - if ((!$this->datas->xml_loader_ids || !is_array($this->datas->xml_loader_ids)) && ($xml_ids = Tools::jsonDecode(Configuration::get('PS_INSTALL_XML_LOADERS_ID'), true))) { + if ((!$this->datas->xml_loader_ids || !is_array($this->datas->xml_loader_ids)) && ($xml_ids = json_decode(Configuration::get('PS_INSTALL_XML_LOADERS_ID'), true))) { $this->datas->xml_loader_ids = $xml_ids; } diff --git a/install/controllers/http/system.php b/install/controllers/http/system.php index 55b449ca5..1a1a7d4e3 100644 --- a/install/controllers/http/system.php +++ b/install/controllers/http/system.php @@ -99,6 +99,7 @@ class InstallControllerHttpSystem extends InstallControllerHttp 'max_execution_time' => $this->l('In the PHP configuration set max_execution_time to minimum 500'), 'upload_max_filesize' => $this->l('In the PHP configuration set upload_max_filesize to minimum 16M'), 'fopen' => $this->l('Cannot open external URLs (requires allow_url_fopen as On).'), + 'zip' => $this->l('ZIP extension is not enabled'), ) ), array( diff --git a/install/dev/index.phtml b/install/dev/index.phtml index 76984a2b5..0eb7e2be0 100644 --- a/install/dev/index.phtml +++ b/install/dev/index.phtml @@ -113,7 +113,7 @@ $this->loader->setDefaultPath(); ?>
Selectionnez la liste des entités à resynchroniser. Afin d'éviter au maximum les erreurs, sélectionnez uniquement les entitiés que vous avez modifier. diff --git a/install/theme/views/process.phtml b/install/theme/views/process.phtml index 5eace8bb6..8111f5021 100644 --- a/install/theme/views/process.phtml +++ b/install/theme/views/process.phtml @@ -3,7 +3,7 @@ diff --git a/install/upgrade/classes/AddConfToFile.php b/install/upgrade/classes/AddConfToFile.php index f2525b4d0..d88678740 100644 --- a/install/upgrade/classes/AddConfToFile.php +++ b/install/upgrade/classes/AddConfToFile.php @@ -86,7 +86,7 @@ class AddConfToFile public function checkString($string) { - if (get_magic_quotes_gpc()) { + if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) { $string = stripslashes($string); } if (!is_numeric($string)) { diff --git a/install/upgrade/php/latin1_database_to_utf8.php b/install/upgrade/php/latin1_database_to_utf8.php index a0fbcc7e5..4b7e6a8bc 100644 --- a/install/upgrade/php/latin1_database_to_utf8.php +++ b/install/upgrade/php/latin1_database_to_utf8.php @@ -25,7 +25,7 @@ */ if (!defined('_PS_MAGIC_QUOTES_GPC_')) { - define('_PS_MAGIC_QUOTES_GPC_', get_magic_quotes_gpc()); + define('_PS_MAGIC_QUOTES_GPC_', function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()); } if (!defined('_PS_MYSQL_REAL_ESCAPE_STRING_')) { define('_PS_MYSQL_REAL_ESCAPE_STRING_', function_exists('mysql_real_escape_string')); diff --git a/install/upgrade/php/ps1607_language_code_update.php b/install/upgrade/php/ps1607_language_code_update.php index c5fd639dc..5ac86d4d7 100644 --- a/install/upgrade/php/ps1607_language_code_update.php +++ b/install/upgrade/php/ps1607_language_code_update.php @@ -31,7 +31,7 @@ function ps1607_language_code_update() if (is_array($langs) && $langs) { foreach ($langs as $lang) { if (Tools::strlen($lang['language_code']) == 2) { - $result = Tools::jsonDecode(Tools::file_get_contents('https://www.prestashop.com/download/lang_packs/get_language_pack.php?version='._PS_VERSION_.'&iso_lang='.Tools::strtolower($lang['iso_code']))); + $result = json_decode(Tools::file_get_contents('https://www.prestashop.com/download/lang_packs/get_language_pack.php?version='._PS_VERSION_.'&iso_lang='.Tools::strtolower($lang['iso_code']))); if ($result && !isset($result->error) && Tools::strlen($result->language_code) > 2) { Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'lang` SET `language_code` = \''.pSQL($result->language_code).'\' WHERE `id_lang` = '.(int)$lang['id_lang']).' LIMIT 1'; } diff --git a/modules/blockcart/blockcart.php b/modules/blockcart/blockcart.php index 2ec384629..7a3fe31ad 100644 --- a/modules/blockcart/blockcart.php +++ b/modules/blockcart/blockcart.php @@ -224,7 +224,8 @@ class blockcart extends Module } $this->assignContentVars($params); - $res = Tools::jsonDecode($this->display(__FILE__, 'blockcart-json.tpl'), true); + + $res = json_decode(Tools::removeHtmlComments($this->display(__FILE__, 'blockcart-json.tpl')), true); if (isset($params['cookie']->avail_rooms)) { $res['avail_rooms'] = $params['cookie']->avail_rooms; @@ -237,7 +238,7 @@ class blockcart extends Module $res['crossSelling'] = $this->display(__FILE__, 'crossselling.tpl'); } - $res = Tools::jsonEncode($res); + $res = json_encode($res); return $res; } @@ -249,7 +250,7 @@ class blockcart extends Module } $this->assignContentVars(array('cookie' => $this->context->cookie, 'cart' => $this->context->cart)); - $params['json'] = $this->display(__FILE__, 'blockcart-json.tpl'); + $params['json'] = Tools::removeHtmlComments($this->display(__FILE__, 'blockcart-json.tpl')); } public function hookHeader() diff --git a/modules/blockcart/checkroomavailabilityajaxprocess.php b/modules/blockcart/checkroomavailabilityajaxprocess.php index 51efaabd4..6fdcb30b0 100644 --- a/modules/blockcart/checkroomavailabilityajaxprocess.php +++ b/modules/blockcart/checkroomavailabilityajaxprocess.php @@ -57,21 +57,21 @@ break; } } - die(Tools::jsonEncode(array('status'=>'success', 'avail_rooms'=>$total_available_rooms))); + die(json_encode(array('status'=>'success', 'avail_rooms'=>$total_available_rooms))); } else { - die(Tools::jsonEncode(array('status'=>'failed1'))); + die(json_encode(array('status'=>'failed1'))); } } else { - die(Tools::jsonEncode(array('status'=>'unavailable_quantity', 'avail_rooms'=>$total_available_rooms))); + die(json_encode(array('status'=>'unavailable_quantity', 'avail_rooms'=>$total_available_rooms))); } } else { - die(Tools::jsonEncode(array('status'=>'failed2'))); + die(json_encode(array('status'=>'failed2'))); } } else { - die(Tools::jsonEncode(array('status'=>'failed3'))); + die(json_encode(array('status'=>'failed3'))); } } else { - die(Tools::jsonEncode(array('status'=>'failed4'))); + die(json_encode(array('status'=>'failed4'))); } } @@ -94,9 +94,9 @@ $result = $obj_htl_cart_booking_data->deleteCartBookingData($id_cart, $id_product); if ($result) { - die(Tools::jsonEncode(array('status'=>'success', 'avail_rooms'=>$total_available_rooms))); + die(json_encode(array('status'=>'success', 'avail_rooms'=>$total_available_rooms))); } else { - die(Tools::jsonEncode(array('status'=>'failed'))); + die(json_encode(array('status'=>'failed'))); } } @@ -109,10 +109,10 @@ $cart_obj = new Cart($id_cart); $update_cart_product = $cart_obj->updateQty($num_rooms_to_decr_from_cart, $id_product, null, false, $operator = 'down', 0, null, true); if ($update_cart_product) { - die(Tools::jsonEncode(array('status'=>'success', 'msg'=>'successfully cart product updated.'))); + die(json_encode(array('status'=>'success', 'msg'=>'successfully cart product updated.'))); } else { - die(Tools::jsonEncode(array('status'=>'failed', 'msg'=>'error while updating cart product.'))); + die(json_encode(array('status'=>'failed', 'msg'=>'error while updating cart product.'))); } } - die(Tools::jsonEncode(array('status'=>'failed', 'msg'=>'error while deleting room from cart booking table.'))); + die(json_encode(array('status'=>'failed', 'msg'=>'error while deleting room from cart booking table.'))); } diff --git a/modules/blockcart/controllers/front/checkroomavailabilityajaxprocess.php b/modules/blockcart/controllers/front/checkroomavailabilityajaxprocess.php index 081eba2a8..547daedfa 100644 --- a/modules/blockcart/controllers/front/checkroomavailabilityajaxprocess.php +++ b/modules/blockcart/controllers/front/checkroomavailabilityajaxprocess.php @@ -50,7 +50,7 @@ class BlockcartCheckRoomAvailabilityAjaxProcessModuleFrontController extends Mod } } die( - Tools::jsonEncode( + json_encode( array( 'status'=>'success', 'msg'=>'successfully cart product updated.', @@ -60,7 +60,7 @@ class BlockcartCheckRoomAvailabilityAjaxProcessModuleFrontController extends Mod ); } die( - Tools::jsonEncode( + json_encode( array('status'=>'failed', 'msg'=>'error while deleting room from cart booking table.') ) ); diff --git a/modules/blockcategories/controllers/admin/AdminBlockCategoriesController.php b/modules/blockcategories/controllers/admin/AdminBlockCategoriesController.php index 42367ed85..4a95beb6a 100644 --- a/modules/blockcategories/controllers/admin/AdminBlockCategoriesController.php +++ b/modules/blockcategories/controllers/admin/AdminBlockCategoriesController.php @@ -48,7 +48,7 @@ class AdminBlockCategoriesController extends ModuleAdminController } public function ajaxProcessuploadThumbnailImages() - { + { $category = new Category((int)Tools::getValue('id_category')); if (isset($_FILES['thumbnail'])) @@ -74,7 +74,7 @@ class AdminBlockCategoriesController extends ModuleAdminController { $total_errors['name'] = sprintf(Tools::displayError('An error occurred while uploading the image :')); $total_errors['error'] = sprintf(Tools::displayError('You cannot upload more files')); - die(Tools::jsonEncode(array('thumbnail' => array($total_errors)))); + die(json_encode(array('thumbnail' => array($total_errors)))); } foreach ($files as $key => &$file) @@ -99,7 +99,7 @@ class AdminBlockCategoriesController extends ModuleAdminController unset($file['save_path']); if (isset($file['tmp_name'])) - unset($file['tmp_name']); + unset($file['tmp_name']); //Add image preview and delete url $file['image'] = ImageManager::thumbnail(_PS_CAT_IMG_DIR_.(int)$category->id.'-'.$id.'_thumb.jpg', @@ -113,7 +113,7 @@ class AdminBlockCategoriesController extends ModuleAdminController else Tools::clearSmartyCache(); - die(Tools::jsonEncode(array('thumbnail' => $files))); + die(json_encode(array('thumbnail' => $files))); } } } diff --git a/modules/blocklayered/blocklayered-url-indexer.php b/modules/blocklayered/blocklayered-url-indexer.php index bc33f3e59..da474797e 100644 --- a/modules/blocklayered/blocklayered-url-indexer.php +++ b/modules/blocklayered/blocklayered-url-indexer.php @@ -7,5 +7,5 @@ if (substr(Tools::encrypt('blocklayered/index'),0,10) != Tools::getValue('token' die('Bad token'); $blockLayered = new BlockLayered(); -$cursor = Tools::jsonDecode(Tools::getValue('cursor', '{}'), true); +$cursor = json_decode(Tools::getValue('cursor', '{}'), true); echo $blockLayered->indexUrl($cursor, (int)Tools::getValue('truncate')); \ No newline at end of file diff --git a/modules/blocklayered/blocklayered.php b/modules/blocklayered/blocklayered.php index 89c25af64..76e8028fd 100644 --- a/modules/blocklayered/blocklayered.php +++ b/modules/blocklayered/blocklayered.php @@ -1621,7 +1621,7 @@ class BlockLayered extends Module 'template_name' => $template['name'], 'attribute_groups' => $attribute_groups, 'features' => $features, - 'filters' => Tools::jsonEncode($filters), + 'filters' => json_encode($filters), 'total_filters' => 6+count($attribute_groups)+count($features) )); @@ -1862,7 +1862,7 @@ class BlockLayered extends Module break; case 'manufacturer': - $query_filters_where .= ' AND p.id_manufacturer IN ('.implode($selected_filters['manufacturer'], ',').')'; + $query_filters_where .= ' AND p.id_manufacturer IN ('.implode(',', $selected_filters['manufacturer']).')'; break; case 'condition': @@ -2005,7 +2005,7 @@ class BlockLayered extends Module $this->products = array(); else { - $product_per_page = isset($this->context->cookie->nb_item_per_page) ? (int)$this->context->cookie->nb_item_per_page : Configuration::get('PS_PRODUCTS_PER_PAGE'); + $product_per_page = isset($this->context->cookie->nb_item_per_page) ? (int)$this->context->cookie->nb_item_per_page : Configuration::get('PS_PRODUCTS_PER_PAGE'); $n = (int)Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')); $nb_day_new_product = (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20); @@ -3049,8 +3049,8 @@ class BlockLayered extends Module $query_filters = ''; else { - array_walk($filter_value, create_function('&$id_manufacturer', '$id_manufacturer = (int)$id_manufacturer;')); - $query_filters = ' AND p.id_manufacturer IN ('.implode($filter_value, ',').')'; + array_walk($filter_value, function (&$id_manufacturer) {$id_manufacturer = (int)$id_manufacturer;}); + $query_filters = ' AND p.id_manufacturer IN ('.implode(',', $filter_value).')'; } if ($ignore_join) return array('where' => $query_filters); @@ -3177,7 +3177,7 @@ class BlockLayered extends Module $vars = array_merge($vars, array('pagination_bottom' => $smarty->assign('paginationId', 'bottom') ->fetch(_PS_THEME_DIR_.'pagination.tpl'))); /* We are sending an array in jSon to the .js controller, it will update both the filters and the products zones */ - return Tools::jsonEncode($vars); + return json_encode($vars); } public function getProducts($selected_filters, &$products, &$nb_products, &$p, &$n, &$pages_nb, &$start, &$stop, &$range) diff --git a/modules/blockwishlist/controllers/front/mywishlist.php b/modules/blockwishlist/controllers/front/mywishlist.php index 61dab94ea..d94e13b95 100644 --- a/modules/blockwishlist/controllers/front/mywishlist.php +++ b/modules/blockwishlist/controllers/front/mywishlist.php @@ -51,7 +51,7 @@ class BlockWishListMyWishListModuleFrontController extends ModuleFrontController elseif (!empty($action) && method_exists($this, 'ajaxProcess'.Tools::toCamelCase($action))) $this->{'ajaxProcess'.Tools::toCamelCase($action)}(); else - die(Tools::jsonEncode(array('error' => 'method doesn\'t exist'))); + die(json_encode(array('error' => 'method doesn\'t exist'))); } /** @@ -150,7 +150,7 @@ class BlockWishListMyWishListModuleFrontController extends ModuleFrontController public function ajaxProcessDeleteList() { if (!$this->context->customer->isLogged()) - die(Tools::jsonEncode(array('success' => false, + die(json_encode(array('success' => false, 'error' => $this->module->l('You aren\'t logged in', 'mywishlist')))); $default = Tools::getIsset('default'); @@ -165,7 +165,7 @@ class BlockWishListMyWishListModuleFrontController extends ModuleFrontController $wishlist->delete(); } else - die(Tools::jsonEncode(array('success' => false, + die(json_encode(array('success' => false, 'error' => $this->module->l('Cannot delete this wishlist', 'mywishlist')))); if ($default_change) @@ -173,19 +173,19 @@ class BlockWishListMyWishListModuleFrontController extends ModuleFrontController $array = WishList::getDefault($id_customer); if (count($array)) - die(Tools::jsonEncode(array( + die(json_encode(array( 'success' => true, 'id_default' => $array[0]['id_wishlist'] ))); } - die(Tools::jsonEncode(array('success' => true))); + die(json_encode(array('success' => true))); } public function ajaxProcessSetDefault() { if (!$this->context->customer->isLogged()) - die(Tools::jsonEncode(array('success' => false, + die(json_encode(array('success' => false, 'error' => $this->module->l('You aren\'t logged in', 'mywishlist')))); $default = Tools::getIsset('default'); @@ -196,16 +196,16 @@ class BlockWishListMyWishListModuleFrontController extends ModuleFrontController { $wishlist = new WishList((int)$id_wishlist); if (Validate::isLoadedObject($wishlist) && $wishlist->id_customer == $this->context->customer->id && $wishlist->setDefault()) - die(Tools::jsonEncode(array('success' => true))); + die(json_encode(array('success' => true))); } - die(Tools::jsonEncode(array('error' => true))); + die(json_encode(array('error' => true))); } public function ajaxProcessProductChangeWishlist() { if (!$this->context->customer->isLogged()) - die(Tools::jsonEncode(array('success' => false, + die(json_encode(array('success' => false, 'error' => $this->module->l('You aren\'t logged in', 'mywishlist')))); $id_product = (int)Tools::getValue('id_product'); @@ -222,7 +222,7 @@ class BlockWishListMyWishListModuleFrontController extends ModuleFrontController !is_int($priority) || ($priority < 0 && $priority > 2) || !$id_old_wishlist || !$id_new_wishlist || (Validate::isLoadedObject($new_wishlist) && $new_wishlist->id_customer != $this->context->customer->id) || (Validate::isLoadedObject($old_wishlist) && $old_wishlist->id_customer != $this->context->customer->id)) - die(Tools::jsonEncode(array('success' => false, 'error' => $this->module->l('Error while moving product to another list', 'mywishlist')))); + die(json_encode(array('success' => false, 'error' => $this->module->l('Error while moving product to another list', 'mywishlist')))); $res = true; $check = (int)Db::getInstance()->getValue('SELECT quantity FROM '._DB_PREFIX_.'wishlist_product @@ -240,7 +240,7 @@ class BlockWishListMyWishListModuleFrontController extends ModuleFrontController } if (!$res) - die(Tools::jsonEncode(array('success' => false, 'error' => $this->module->l('Error while moving product to another list', 'mywishlist')))); - die(Tools::jsonEncode(array('success' => true, 'msg' => $this->module->l('The product has been correctly moved', 'mywishlist')))); + die(json_encode(array('success' => false, 'error' => $this->module->l('Error while moving product to another list', 'mywishlist')))); + die(json_encode(array('success' => true, 'msg' => $this->module->l('The product has been correctly moved', 'mywishlist')))); } } diff --git a/modules/graphnvd3/graphnvd3.php b/modules/graphnvd3/graphnvd3.php index 2c0f4e277..b9cd126d6 100644 --- a/modules/graphnvd3/graphnvd3.php +++ b/modules/graphnvd3/graphnvd3.php @@ -176,6 +176,6 @@ class GraphNvD3 extends ModuleGraphEngine $array['data'][] = array('values' => $nvd3_values, 'key' => $this->_titles['main'][$layer]); } } - die(preg_replace('/"([0-9]+)"/', '$1', Tools::jsonEncode($array))); + die(preg_replace('/"([0-9]+)"/', '$1', json_encode($array))); } } diff --git a/modules/gridhtml/gridhtml.php b/modules/gridhtml/gridhtml.php index 10b2ecec6..d0f68efd4 100644 --- a/modules/gridhtml/gridhtml.php +++ b/modules/gridhtml/gridhtml.php @@ -43,19 +43,19 @@ class GridHtml extends ModuleGridEngine $this->version = '1.3.1'; $this->author = 'PrestaShop'; $this->need_instance = 0; - + Module::__construct(); - + $this->displayName = $this->l('Simple HTML table display'); $this->description = $this->l('Allows the statistics system to display data in a grid.'); } } - + function install() { return (parent::install() AND $this->registerHook('GridEngine')); } - + public static function hookGridEngine($params, $grider) { self::$_columns = $params['columns']; @@ -112,7 +112,7 @@ class GridHtml extends ModuleGridEngine $("#grid_1 tbody").append("'.$params['emptyMsg'].'"); }); } - + function gridNextPage(url) { var from = url.match(/&start=[0-9]+/i); @@ -123,7 +123,7 @@ class GridHtml extends ModuleGridEngine url = url.replace(/&start=[0-9]+/i, "") + from; getGridData(url); } - + function gridPrevPage(url) { var from = url.match(/&start=[0-9]+/i); @@ -145,46 +145,46 @@ class GridHtml extends ModuleGridEngine '; return $html; } - + public function setColumnsInfos(&$infos) { } - + public function setValues($values) { $this->_values = $values; } - + public function setTitle($title) { $this->_title = $title; } - + public function setSize($width, $height) { $this->_width = $width; $this->_height = $height; } - + public function setTotalCount($totalCount) { $this->_totalCount = $totalCount; } - + public function setLimit($start, $limit) { $this->_start = (int)$start; $this->_limit = (int)$limit; } - + public function render() { - echo Tools::jsonEncode(array( + echo json_encode(array( 'total' => $this->_totalCount, 'from' => min($this->_start + 1, $this->_totalCount), 'to' => min($this->_start + $this->_limit, $this->_totalCount), 'values' => $this->_values )); - } + } } diff --git a/modules/hotelreservationsystem/classes/HotelBookingDetail.php b/modules/hotelreservationsystem/classes/HotelBookingDetail.php index 5fac0e8d7..fa67c2e20 100644 --- a/modules/hotelreservationsystem/classes/HotelBookingDetail.php +++ b/modules/hotelreservationsystem/classes/HotelBookingDetail.php @@ -64,6 +64,10 @@ class HotelBookingDetail extends ObjectModel public $date_add; public $date_upd; + const STATUS_ALLOTED = 1; + const STATUS_CHECKED_IN = 2; + const STATUS_CHECKED_OUT = 3; + public static $definition = array( 'table' => 'htl_booking_detail', 'primary' => 'id', @@ -273,7 +277,7 @@ class HotelBookingDetail extends ObjectModel $sql = 'SELECT bd.`id_product`, bd.`id_room`, bd.`id_hotel`, bd.`id_customer`, bd.`booking_type`, bd.`id_status` AS booking_status, bd.`comment`, rf.`room_num`, bd.`date_from`, bd.`date_to` FROM `'._DB_PREFIX_.'htl_booking_detail` AS bd INNER JOIN `'._DB_PREFIX_.'htl_room_information` AS rf ON (rf.`id` = bd.`id_room`) - WHERE bd.`id_hotel`='.(int)$hotel_id.' AND bd.`id_product` ='.(int)$room_type['id_product'].' AND bd.`is_refunded` = 0 AND bd.`is_back_order` = 0 AND IF(bd.`id_status` = 3, bd.`date_from` <= \''.pSQL($date_from).'\' AND bd.`check_out` >= \''.pSQL($date_to).'\', bd.`date_from` <= \''.pSQL($date_from).'\' AND bd.date_to >= \''.pSQL($date_to).'\')'; + WHERE bd.`id_hotel`='.(int)$hotel_id.' AND bd.`id_product` ='.(int)$room_type['id_product'].' AND bd.`is_refunded` = 0 AND bd.`is_back_order` = 0 AND IF(bd.`id_status` = '. self::STATUS_CHECKED_OUT .', bd.`date_from` <= \''.pSQL($date_from).'\' AND bd.`check_out` >= \''.pSQL($date_to).'\', bd.`date_from` <= \''.pSQL($date_from).'\' AND bd.date_to >= \''.pSQL($date_to).'\')'; $booked_rooms = Db::getInstance()->executeS($sql); @@ -301,12 +305,12 @@ class HotelBookingDetail extends ObjectModel if ($search_unavai) { $sql1 = 'SELECT `id_product`, `id_hotel`, `room_num`, `comment` AS `room_comment` FROM `'._DB_PREFIX_.'htl_room_information` - WHERE `id_hotel`='.(int)$hotel_id.' AND `id_product` ='.(int)$room_type['id_product'].' AND `id_status` = 2'; + WHERE `id_hotel`='.(int)$hotel_id.' AND `id_product` ='.(int)$room_type['id_product'].' AND `id_status` = '. self::STATUS_CHECKED_IN; $sql2 = 'SELECT hri.`id_product`, hri.`id_hotel`, hri.`room_num`, hri.`comment` AS `room_comment` FROM `'._DB_PREFIX_.'htl_room_information` AS hri INNER JOIN `'._DB_PREFIX_.'htl_room_disable_dates` AS hrdd ON (hrdd.`id_room_type` = hri.`id_product` AND hrdd. id_room = hri.`id`) - WHERE hri.`id_hotel`='.$hotel_id.' AND hri.`id_product` ='.$room_type['id_product'].' AND hri.`id_status` = 3 AND hrdd.`date_from` <= \''.pSql($date_from).'\' AND hrdd.`date_to` >= \''.pSql($date_to).'\''; + WHERE hri.`id_hotel`='.$hotel_id.' AND hri.`id_product` ='.$room_type['id_product'].' AND hri.`id_status` = '. self::STATUS_CHECKED_OUT .' AND hrdd.`date_from` <= \''.pSql($date_from).'\' AND hrdd.`date_to` >= \''.pSql($date_to).'\''; $sql = $sql1.' UNION '.$sql2; @@ -317,7 +321,7 @@ class HotelBookingDetail extends ObjectModel if ($search_available) { $exclude_ids = 'SELECT `id_room` FROM `'._DB_PREFIX_.'htl_booking_detail` - WHERE `is_back_order` = 0 AND `is_refunded` = 0 AND IF(`id_status` = 3, ( + WHERE `is_back_order` = 0 AND `is_refunded` = 0 AND IF(`id_status` = '. self::STATUS_CHECKED_OUT.', ( (DATE_FORMAT(`check_out`, "%Y-%m-%d") > \''.pSQL($date_from).'\' AND DATE_FORMAT(`check_out`, "%Y-%m-%d") <= \''.PSQL($date_to).'\') AND ( (`date_from` <= \''.pSQL($date_from).'\' AND `check_out` > \''.pSQL($date_from).'\' AND `check_out` <= \''.PSQL($date_to).'\') OR (`date_from` >= \''.pSQL($date_from).'\' AND `check_out` > \''.pSQL($date_from).'\' AND `check_out` <= \''.pSQL($date_to).'\') OR @@ -343,13 +347,13 @@ class HotelBookingDetail extends ObjectModel SELECT hri.`id` AS id_room FROM `'._DB_PREFIX_.'htl_room_information` AS hri INNER JOIN `'._DB_PREFIX_.'htl_room_disable_dates` AS hrdd ON (hrdd.`id_room_type` = hri.`id_product` AND hrdd.`id_room` = hri.`id`) - WHERE hri.`id_hotel`='.(int)$hotel_id.' AND hri.`id_product` ='.(int)$room_type['id_product'].' AND hri.`id_status` = 3 AND (hrdd.`date_from` <= \''.pSql($date_to).'\' AND hrdd.`date_to` >= \''.pSql($date_from).'\')'; + WHERE hri.`id_hotel`='.(int)$hotel_id.' AND hri.`id_product` ='.(int)$room_type['id_product'].' AND hri.`id_status` = '. self::STATUS_CHECKED_OUT .' AND (hrdd.`date_from` <= \''.pSql($date_to).'\' AND hrdd.`date_to` >= \''.pSql($date_from).'\')'; $selectAvailRoomSearch = 'SELECT ri.`id` AS `id_room`, ri.`id_product`, ri.`id_hotel`, ri.`room_num`, ri.`comment` AS `room_comment`'; $joinAvailRoomSearch = ''; - $whereAvailRoomSearch = 'WHERE ri.`id_hotel`='.(int)$hotel_id.' AND ri.`id_product`='.(int)$room_type['id_product'].' AND ri.`id_status` != 2 AND ri.`id` NOT IN ('.$exclude_ids.')'; + $whereAvailRoomSearch = 'WHERE ri.`id_hotel`='.(int)$hotel_id.' AND ri.`id_product`='.(int)$room_type['id_product'].' AND ri.`id_status` != '. self::STATUS_CHECKED_IN .' AND ri.`id` NOT IN ('.$exclude_ids.')'; $groupByAvailRoomSearch = ''; $orderByAvailRoomSearch = ''; @@ -385,10 +389,10 @@ class HotelBookingDetail extends ObjectModel } if ($search_partial) { - $sql1 = 'SELECT bd.`id_product`, bd.`id_room`, bd.`id_hotel`, bd.`id_customer`, bd.`booking_type`, bd.`id_status` AS booking_status, bd.`comment` AS `room_comment`, rf.`room_num`, bd.`date_from`, IF(bd.`id_status` = 3, bd.`check_out`, bd.`date_to`) AS `date_to` + $sql1 = 'SELECT bd.`id_product`, bd.`id_room`, bd.`id_hotel`, bd.`id_customer`, bd.`booking_type`, bd.`id_status` AS booking_status, bd.`comment` AS `room_comment`, rf.`room_num`, bd.`date_from`, IF(bd.`id_status` = '. self::STATUS_CHECKED_OUT .', bd.`check_out`, bd.`date_to`) AS `date_to` FROM `'._DB_PREFIX_.'htl_booking_detail` AS bd INNER JOIN `'._DB_PREFIX_.'htl_room_information` AS rf ON (rf.`id` = bd.`id_room`) - WHERE bd.`id_hotel`='.(int)$hotel_id.' AND bd.`id_product`='.(int)$room_type['id_product'].' AND rf.`id_status` != 2 AND bd.`is_back_order` = 0 AND bd.`is_refunded` = 0 AND IF(bd.`id_status` = 3, ( + WHERE bd.`id_hotel`='.(int)$hotel_id.' AND bd.`id_product`='.(int)$room_type['id_product'].' AND rf.`id_status` != '. self::STATUS_CHECKED_IN .' AND bd.`is_back_order` = 0 AND bd.`is_refunded` = 0 AND IF(bd.`id_status` = '. self::STATUS_CHECKED_OUT .', ( (DATE_FORMAT(`check_out`, "%Y-%m-%d") > \''.pSQL($date_from).'\' AND DATE_FORMAT(`check_out`, "%Y-%m-%d") < \''.PSQL($date_to).'\') AND ( (bd.`date_from` <= \''.pSQL($date_from).'\' AND bd.`check_out` > \''.pSQL($date_from).'\' AND bd.`check_out` < \''.pSQL($date_to).'\') OR (bd.`date_from` > \''.pSQL($date_from).'\' AND bd.`date_from` < \''.pSQL($date_to).'\' AND bd.`check_out` >= \''.pSQL($date_to).'\') OR @@ -404,7 +408,7 @@ class HotelBookingDetail extends ObjectModel FROM `'._DB_PREFIX_.'htl_room_information` AS hri INNER JOIN `'._DB_PREFIX_.'htl_room_disable_dates` AS hrdd ON (hrdd.`id_room_type` = hri.`id_product` AND hrdd.`id_room` = hri.`id`) WHERE hri.`id_hotel`='.(int)$hotel_id.' AND hri.`id_product`='.(int)$room_type['id_product'].' AND - hri.`id_status` = 3 AND ( + hri.`id_status` = '. self::STATUS_CHECKED_OUT .' AND ( (hrdd.`date_from` <= \''.pSQL($date_from).'\' AND hrdd.`date_to` > \''.pSQL($date_from).'\' AND hrdd.`date_to` < \''.pSQL($date_to).'\') OR (hrdd.`date_from` > \''.pSQL($date_from).'\' AND hrdd.`date_from` < \''.pSQL($date_to).'\' AND hrdd.`date_to` >= \''.pSQL($date_to).'\') OR (hrdd.`date_from` > \''.pSQL($date_from).'\' AND hrdd.`date_from` < \''.pSQL($date_to).'\' AND hrdd.`date_to` < \''.pSQL($date_to).'\') @@ -764,12 +768,12 @@ class HotelBookingDetail extends ObjectModel $table = 'htl_booking_detail'; // create date to update in the table - if ($new_status == 2) { + if ($new_status == self::STATUS_CHECKED_IN) { $data = array( 'id_status' => $new_status, 'check_in' => ($status_date > $date_to ? $date_to : $status_date) ); - } elseif ($new_status == 3) { + } elseif ($new_status == self::STATUS_CHECKED_OUT) { $data = array( 'id_status' => $new_status, 'check_out' => ($status_date > $date_to ? $date_to : $status_date) @@ -947,14 +951,14 @@ class HotelBookingDetail extends ObjectModel if (isset($current_admin_cart_id) && $current_admin_cart_id) { $sql = 'SELECT `id` AS `id_room`, `id_product`, `id_hotel`, `room_num`, `comment` AS `room_comment` FROM `'._DB_PREFIX_.'htl_room_information` - WHERE `id_hotel`='.(int)$hotel_id.' AND `id_product`='.(int)$room_type.' AND id_status = 1 + WHERE `id_hotel`='.(int)$hotel_id.' AND `id_product`='.(int)$room_type.' AND id_status = '. self::STATUS_ALLOTED .' AND `id` NOT IN (SELECT `id_room` FROM `'._DB_PREFIX_.'htl_booking_detail` WHERE `date_from` < \''. pSQL($date_to).'\' AND `date_to` > \''.pSQL($date_from).'\' AND `is_refunded`=0 AND `is_back_order`=0) AND `id` NOT IN (SELECT `id_room` FROM `'._DB_PREFIX_.'htl_cart_booking_data` WHERE `id_cart`='. (int)$current_admin_cart_id.')'; } else { $sql = 'SELECT `id` AS `id_room`, `id_product`, `id_hotel`, `room_num`, `comment` AS `room_comment` - FROM `'._DB_PREFIX_.'htl_room_information` WHERE `id_hotel`='.(int)$hotel_id.' AND `id_product`='.(int)$room_type.' AND id_status = 1 AND `id` NOT IN (SELECT `id_room` FROM `'._DB_PREFIX_.'htl_booking_detail` WHERE `date_from` < \''.pSQL($date_to).'\' AND `date_to` > \''.pSQL($date_from).'\' AND `is_refunded`=0 AND `is_back_order`=0)'; + FROM `'._DB_PREFIX_.'htl_room_information` WHERE `id_hotel`='.(int)$hotel_id.' AND `id_product`='.(int)$room_type.' AND id_status = '. self::STATUS_ALLOTED .' AND `id` NOT IN (SELECT `id_room` FROM `'._DB_PREFIX_.'htl_booking_detail` WHERE `date_from` < \''.pSQL($date_to).'\' AND `date_to` > \''.pSQL($date_from).'\' AND `is_refunded`=0 AND `is_back_order`=0)'; } $avail_rooms = Db::getInstance()->executeS($sql); if ($avail_rooms) { @@ -976,7 +980,7 @@ class HotelBookingDetail extends ObjectModel public function getAvailableRoomsForSwapping($date_from, $date_to, $room_type, $hotel_id, $id_room) { $sql = 'SELECT `id` AS `id_room`, `id_product`, `id_hotel`, `room_num`, `comment` AS `room_comment` FROM `'._DB_PREFIX_.'htl_room_information` WHERE `id_hotel`='.(int)$hotel_id.' AND `id_product`='.(int)$room_type. - ' AND `id_status` = 1 AND `id` IN (SELECT `id_room` FROM `'._DB_PREFIX_.'htl_booking_detail` WHERE `date_from` = \''.pSQL($date_from).'\' AND `date_to` = \''.pSQL($date_to).'\' AND `id_room`!='.(int)$id_room.' AND `is_refunded`=0 AND `is_back_order`=0)'; + ' AND `id_status` = '. self::STATUS_ALLOTED .' AND `id` IN (SELECT `id_room` FROM `'._DB_PREFIX_.'htl_booking_detail` WHERE `date_from` = \''.pSQL($date_from).'\' AND `date_to` = \''.pSQL($date_to).'\' AND `id_room`!='.(int)$id_room.' AND `is_refunded`=0 AND `is_back_order`=0)'; return Db::getInstance()->executeS($sql); } @@ -1660,7 +1664,7 @@ class HotelBookingDetail extends ObjectModel $objHtlBooking->id_hotel = $objCartBooking->id_hotel; $objHtlBooking->id_customer = $cart->id_customer; $objHtlBooking->booking_type = $objCartBooking->booking_type; - $objHtlBooking->id_status = 1; + $objHtlBooking->id_status = self::STATUS_ALLOTED; $objHtlBooking->comment = $objCartBooking->comment; // For Back Order(Because of cart lock) @@ -1753,15 +1757,37 @@ class HotelBookingDetail extends ObjectModel ); } - public function getRoomBookingData($idRoom, $idOrder) + public function getRoomBookingData($idRoom, $idOrder, $date_from, $date_to) { $sql = 'SELECT `id_product`, `id_order_detail`, `id_hotel`, `id_customer`, `booking_type`, `id_status`, `check_in`, `check_out` FROM `'._DB_PREFIX_.'htl_booking_detail` - WHERE `id_order`='.(int)$idOrder.' AND `id_room`='.(int)$idRoom; + WHERE `id_order`='.(int)$idOrder.' AND `id_room`='.(int)$idRoom.' + AND `date_from`=\''.pSQL($date_from).'\' AND `date_to`= \''.pSQL($date_to).'\''; return Db::getInstance()->getRow($sql); } + public static function getAllHotelOrderStatus() + { + $moduleInstance = Module::getInstanceByName('hotelreservationsystem'); + + $pages = array( + 'STATUS_ALLOTED' => array( + 'id_status' => self::STATUS_ALLOTED, + 'name' => $moduleInstance->l('Alloted', 'hotelreservationsystem') + ), + 'STATUS_CHECKED_IN' => array( + 'id_status' => self::STATUS_CHECKED_IN, + 'name' => $moduleInstance->l('Checked In', 'hotelreservationsystem') + ), + 'STATUS_CHECKED_OUT' => array( + 'id_status' => self::STATUS_CHECKED_OUT, + 'name' => $moduleInstance->l('Checked Out', 'hotelreservationsystem') + ), + ); + return $pages; + } + // Webservice funcions public function getWsBookingExtraDemands() { diff --git a/modules/hotelreservationsystem/classes/HotelBranchInformation.php b/modules/hotelreservationsystem/classes/HotelBranchInformation.php index 1056deafe..fb4561107 100644 --- a/modules/hotelreservationsystem/classes/HotelBranchInformation.php +++ b/modules/hotelreservationsystem/classes/HotelBranchInformation.php @@ -840,7 +840,7 @@ class HotelBranchInformation extends ObjectModel libxml_use_internal_errors(true); $xml = simplexml_load_string(utf8_decode($postData)); - $hotelData = Tools::jsonDecode(Tools::jsonEncode($xml)); + $hotelData = json_decode(json_encode($xml)); if (isset($hotelData->hotel->max_order_date)) { if ($maxOrderDate = $hotelData->hotel->max_order_date) { $this->setWsMaxOrderDate($maxOrderDate); @@ -863,7 +863,7 @@ class HotelBranchInformation extends ObjectModel libxml_use_internal_errors(true); $xml = simplexml_load_string(utf8_decode($postData)); - $hotelData = Tools::jsonDecode(Tools::jsonEncode($xml)); + $hotelData = json_decode(json_encode($xml)); if (isset($hotelData->hotel->max_order_date)) { if ($maxOrderDate = $hotelData->hotel->max_order_date) { $this->setWsMaxOrderDate($maxOrderDate); diff --git a/modules/hotelreservationsystem/classes/HotelCartBookingData.php b/modules/hotelreservationsystem/classes/HotelCartBookingData.php index fc234d227..61cd21458 100644 --- a/modules/hotelreservationsystem/classes/HotelCartBookingData.php +++ b/modules/hotelreservationsystem/classes/HotelCartBookingData.php @@ -764,7 +764,7 @@ class HotelCartBookingData extends ObjectModel AND fp.`active`=1 AND fp.`date_from` <= \''.pSQL($date).'\' AND fp.`date_to` >= \''.pSQL($date).'\'' )) { foreach ($featurePrice as $fRow) { - $specialDays = Tools::jsonDecode($fRow['special_days']); + $specialDays = json_decode($fRow['special_days']); if (in_array(strtolower(date('D', strtotime($date))), $specialDays)) { return $fRow; } @@ -1105,7 +1105,7 @@ class HotelCartBookingData extends ObjectModel if ($getTotalPrice) { if ($roomTypeDemands['extra_demands'] - && ($extraDemand = Tools::jsonDecode($roomTypeDemands['extra_demands'], true)) + && ($extraDemand = json_decode($roomTypeDemands['extra_demands'], true)) ) { $totalDemandsPrice += $objRoomDemandPrice->getRoomTypeDemandsTotalPrice( $roomTypeDemands['id_product'], @@ -1116,7 +1116,7 @@ class HotelCartBookingData extends ObjectModel ); } } else { - $roomTypeDemands['extra_demands'] = Tools::jsonDecode( + $roomTypeDemands['extra_demands'] = json_decode( $roomTypeDemands['extra_demands'], true ); @@ -1146,7 +1146,7 @@ class HotelCartBookingData extends ObjectModel foreach ($roomTypeDemands as $key => &$demand) { if ($getTotalPrice) { if ($demand['extra_demands'] - && ($extraDemand = Tools::jsonDecode($demand['extra_demands'], true)) + && ($extraDemand = json_decode($demand['extra_demands'], true)) ) { $totalDemandsPrice += $objRoomDemandPrice->getRoomTypeDemandsTotalPrice( $demand['id_product'], @@ -1157,7 +1157,7 @@ class HotelCartBookingData extends ObjectModel ); } } else { - $demand['extra_demands'] = Tools::jsonDecode( + $demand['extra_demands'] = json_decode( $demand['extra_demands'], true ); @@ -1193,7 +1193,7 @@ class HotelCartBookingData extends ObjectModel // Webservice :: get extra demands for the cart booking public function getWsExtraDemands() { - $extraDemands = Tools::jsonDecode($this->extra_demands, true); + $extraDemands = json_decode($this->extra_demands, true); if (count($extraDemands)) { foreach ($extraDemands as &$demnad) { $demnad['id'] = $demnad['id_global_demand']; diff --git a/modules/hotelreservationsystem/classes/HotelHelper.php b/modules/hotelreservationsystem/classes/HotelHelper.php index ea2940ce4..909dc43ab 100644 --- a/modules/hotelreservationsystem/classes/HotelHelper.php +++ b/modules/hotelreservationsystem/classes/HotelHelper.php @@ -293,18 +293,6 @@ class HotelHelper return true; } - public function insertHotelOrderStatus() - { - $order_status_arr = array('Alloted','Checked In','Checked Out'); - foreach ($order_status_arr as $key => $value) { - $obj_order_status = new HotelOrderStatus(); - $obj_order_status->status = $value; - $obj_order_status->save(); - } - - return true; - } - public function insertHotelRoomAllotmentType() { $altment_type_arr = array('Random Allotment','Manual Allotment'); diff --git a/modules/hotelreservationsystem/classes/HotelOrderRestrictDate.php b/modules/hotelreservationsystem/classes/HotelOrderRestrictDate.php index a51eb1b82..3d490af2c 100644 --- a/modules/hotelreservationsystem/classes/HotelOrderRestrictDate.php +++ b/modules/hotelreservationsystem/classes/HotelOrderRestrictDate.php @@ -54,10 +54,8 @@ class HotelOrderRestrictDate extends ObjectModel $obj_ord_rest = new self(); $order_restrict_data = $obj_ord_rest->getDataByHotelId($id_hotel); - $max_order_date_restr = $order_restrict_data['max_order_date']; - - if (isset($max_order_date_restr) && $max_order_date_restr) { - $max_order_date = $max_order_date_restr; + if (isset($order_restrict_data['max_order_date']) && $order_restrict_data['max_order_date']) { + $max_order_date = $order_restrict_data['max_order_date']; } elseif (isset($global_max_order_date) && $global_max_order_date) { $max_order_date = $global_max_order_date; } else { diff --git a/modules/hotelreservationsystem/classes/HotelOrderStatus.php b/modules/hotelreservationsystem/classes/HotelOrderStatus.php deleted file mode 100644 index 09c527cce..000000000 --- a/modules/hotelreservationsystem/classes/HotelOrderStatus.php +++ /dev/null @@ -1,46 +0,0 @@ - -* @copyright 2010-2020 Webkul IN -* @license https://store.webkul.com/license.html -*/ - -class HotelOrderStatus extends ObjectModel -{ - public $id; - public $status; - - public static $definition = array( - 'table' => 'htl_order_status', - 'primary' => 'id', - 'fields' => array( - 'status' => array('type' => self::TYPE_STRING), - ), - ); - - /** - * [getAllHotelOrderStatus :: To get array all possible order statuses] - * @return [array|boolean] [If data found then Returns array of the order statuses else returns false] - */ - public static function getAllHotelOrderStatus() - { - $result = Db::getInstance()->executeS("SELECT * FROM `"._DB_PREFIX_."htl_order_status`"); - if ($result) { - return $result; - } - return false; - } -} diff --git a/modules/hotelreservationsystem/classes/HotelRoomTypeDemandPrice.php b/modules/hotelreservationsystem/classes/HotelRoomTypeDemandPrice.php index 53a2ce945..522b78584 100644 --- a/modules/hotelreservationsystem/classes/HotelRoomTypeDemandPrice.php +++ b/modules/hotelreservationsystem/classes/HotelRoomTypeDemandPrice.php @@ -143,7 +143,7 @@ class HotelRoomTypeDemandPrice extends ObjectModel } if ($cartChanged) { if (Validate::isLoadedObject($objCartBooking = new HotelCartBookingData($demandInfo['id']))) { - $objCartBooking->extra_demands = Tools::jsonEncode($demandInfo['extra_demands']); + $objCartBooking->extra_demands = json_encode($demandInfo['extra_demands']); $objCartBooking->save(); } } diff --git a/modules/hotelreservationsystem/classes/HotelRoomTypeGlobalDemand.php b/modules/hotelreservationsystem/classes/HotelRoomTypeGlobalDemand.php index 285cbaa27..b5b6bfa17 100644 --- a/modules/hotelreservationsystem/classes/HotelRoomTypeGlobalDemand.php +++ b/modules/hotelreservationsystem/classes/HotelRoomTypeGlobalDemand.php @@ -100,7 +100,7 @@ class HotelRoomTypeGlobalDemand extends ObjectModel } if ($cartChanged) { if (Validate::isLoadedObject($objCartBooking = new HotelCartBookingData($demandInfo['id']))) { - $objCartBooking->extra_demands = Tools::jsonEncode($demandInfo['extra_demands']); + $objCartBooking->extra_demands = json_encode($demandInfo['extra_demands']); $objCartBooking->save(); } } diff --git a/modules/hotelreservationsystem/classes/HotelRoomTypeGlobalDemandAdvanceOption.php b/modules/hotelreservationsystem/classes/HotelRoomTypeGlobalDemandAdvanceOption.php index 398aa7545..282139aff 100644 --- a/modules/hotelreservationsystem/classes/HotelRoomTypeGlobalDemandAdvanceOption.php +++ b/modules/hotelreservationsystem/classes/HotelRoomTypeGlobalDemandAdvanceOption.php @@ -80,7 +80,7 @@ class HotelRoomTypeGlobalDemandAdvanceOption extends ObjectModel } if ($cartChanged) { if (Validate::isLoadedObject($objCartBooking = new HotelCartBookingData($demandInfo['id']))) { - $objCartBooking->extra_demands = Tools::jsonEncode($demandInfo['extra_demands']); + $objCartBooking->extra_demands = json_encode($demandInfo['extra_demands']); $objCartBooking->save(); } } diff --git a/modules/hotelreservationsystem/classes/QloRoomType.php b/modules/hotelreservationsystem/classes/QloRoomType.php index 3aa606312..c5bc3ac02 100644 --- a/modules/hotelreservationsystem/classes/QloRoomType.php +++ b/modules/hotelreservationsystem/classes/QloRoomType.php @@ -156,7 +156,7 @@ class QloRoomType extends QloWebservice // } // // convert object to array - // $address = Tools::jsonDecode(Tools::jsonEncode($address), true); + // $address = json_decode(json_encode($address), true); // $this->output .= $this->objOutput->getObjectRender()->renderNodeHeader('address', array()); // $address['country'] = Country::getNameById($this->id_lang, $address['id_country']); diff --git a/modules/hotelreservationsystem/classes/WebserviceSpecificManagementQlo.php b/modules/hotelreservationsystem/classes/WebserviceSpecificManagementQlo.php index 959aa6c45..11280b267 100644 --- a/modules/hotelreservationsystem/classes/WebserviceSpecificManagementQlo.php +++ b/modules/hotelreservationsystem/classes/WebserviceSpecificManagementQlo.php @@ -80,7 +80,7 @@ class WebserviceSpecificManagementQlo implements WebserviceSpecificManagementInt $outputXML = $this->objOutput->getObjectRender()->overrideContent($this->output); if (isset($this->wsObject->urlFragments['outputformat']) && $this->wsObject->urlFragments['outputformat'] == 'json') { $outputXML = simplexml_load_string($outputXML, null, LIBXML_NOCDATA); - $json = Tools::jsonEncode($outputXML); + $json = json_encode($outputXML); $content = preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", $json); header('Content-Type: application/json'); die($content); @@ -153,7 +153,7 @@ class WebserviceSpecificManagementQlo implements WebserviceSpecificManagementInt } } else { // If input type is json - $array = Tools::jsonDecode($inputXML, true); + $array = json_decode($inputXML, true); if (isset($array['json']) && $array['json'] && isset($array[$head])) { return ($head ? $array[$head] : $array); } else { @@ -172,7 +172,7 @@ class WebserviceSpecificManagementQlo implements WebserviceSpecificManagementInt $xmlEntities = $xml->children(); // Convert multi-dimention xml into an array - $array = Tools::jsonDecode(Tools::jsonEncode($xmlEntities), true); + $array = json_decode(json_encode($xmlEntities), true); return ($head ? $array[$head] : $array); } diff --git a/modules/hotelreservationsystem/controllers/admin/AdminAddHotelController.php b/modules/hotelreservationsystem/controllers/admin/AdminAddHotelController.php index 9e943ae9c..b8d9921d9 100644 --- a/modules/hotelreservationsystem/controllers/admin/AdminAddHotelController.php +++ b/modules/hotelreservationsystem/controllers/admin/AdminAddHotelController.php @@ -493,7 +493,7 @@ class AdminAddHotelController extends ModuleAdminController } } } - die(Tools::jsonEncode($states)); + die(json_encode($states)); } public function ajaxProcessUploadHotelImages() @@ -514,19 +514,19 @@ class AdminAddHotelController extends ModuleAdminController $hotelImgPath = _PS_MODULE_DIR_.'hotelreservationsystem/views/img/hotel_img/'; $imageDetail = $objHotelImage->uploadHotelImages($_FILES['hotel_image'], $idHotel, $hotelImgPath); if ($imageDetail) { - die(Tools::jsonEncode($imageDetail)); + die(json_encode($imageDetail)); } else { - die(Tools::jsonEncode(array('hasError' => true))); + die(json_encode(array('hasError' => true))); } } else { die( - Tools::jsonEncode( + json_encode( array('hasError' => true, 'message' => $_FILES['hotel_image']['name'].': '.$invalidImg) ) ); } } else { - die(Tools::jsonEncode(array('hasError' => true))); + die(json_encode(array('hasError' => true))); } } diff --git a/modules/hotelreservationsystem/controllers/admin/AdminHotelFeaturePricesSettings.php b/modules/hotelreservationsystem/controllers/admin/AdminHotelFeaturePricesSettings.php index 24c94a068..27b7f0694 100644 --- a/modules/hotelreservationsystem/controllers/admin/AdminHotelFeaturePricesSettings.php +++ b/modules/hotelreservationsystem/controllers/admin/AdminHotelFeaturePricesSettings.php @@ -190,7 +190,7 @@ class AdminHotelFeaturePricesSettingsController extends ModuleAdminController } } if ($objFeaturePrice->special_days) { - $smartyVars['special_days'] = Tools::jsonDecode($objFeaturePrice->special_days, true); + $smartyVars['special_days'] = json_decode($objFeaturePrice->special_days, true); } $smartyVars['objFeaturePrice'] = $objFeaturePrice; $smartyVars['edit'] = 1; @@ -247,7 +247,7 @@ class AdminHotelFeaturePricesSettingsController extends ModuleAdminController $impactValue = Tools::getValue('impact_value'); $dateSelectionType = Tools::getValue('date_selection_type'); $specificDate = date('Y-m-d', strtotime(Tools::getValue('specific_date'))); - $jsonSpecialDays = Tools::jsonEncode($specialDays); + $jsonSpecialDays = json_encode($specialDays); $defaultLangId = Configuration::get('PS_LANG_DEFAULT'); $objFeaturePricing = new HotelRoomTypeFeaturePricing(); @@ -437,18 +437,18 @@ class AdminHotelFeaturePricesSettingsController extends ModuleAdminController $product['name'].= ' / '.$onjBranchInfo->hotel_name; } } - echo Tools::jsonEncode($productsByName, true); + echo json_encode($productsByName, true); die; } else { die( - Tools::jsonEncode( + json_encode( array('status' => 'failed', 'msg' => $this->l('No match found for entered room type name.')) ) ); } } else { die( - Tools::jsonEncode( + json_encode( array('status' => 'failed', 'msg' => $this->l('No match found for entered room type name.')) ) ); diff --git a/modules/hotelreservationsystem/controllers/admin/AdminHotelRoomsBookingController.php b/modules/hotelreservationsystem/controllers/admin/AdminHotelRoomsBookingController.php index 56eff9819..1d14a138c 100644 --- a/modules/hotelreservationsystem/controllers/admin/AdminHotelRoomsBookingController.php +++ b/modules/hotelreservationsystem/controllers/admin/AdminHotelRoomsBookingController.php @@ -292,7 +292,7 @@ class AdminHotelRoomsBookingController extends ModuleAdminController $hotel_id = Tools::getValue('hotel_id'); $obj_room_type = new HotelRoomType(); $room_type_info = $obj_room_type->getRoomTypeByHotelId($hotel_id, Configuration::get('PS_LANG_DEFAULT'), 1); - die(Tools::jsonEncode($room_type_info)); + die(json_encode($room_type_info)); } public function ajaxProcessAddDataToCart() @@ -412,7 +412,7 @@ class AdminHotelRoomsBookingController extends ModuleAdminController 'id_cart_book_data' => $obj_cart_book_data->id); if ($obj_cart_book_data->id) { - die(Tools::jsonEncode($cart_data)); + die(json_encode($cart_data)); } else { die(0); } @@ -495,7 +495,7 @@ class AdminHotelRoomsBookingController extends ModuleAdminController 'booking_data' => $booking_data, ); } - die(Tools::jsonEncode($cart_data)); + die(json_encode($cart_data)); } else { die(0); } @@ -534,7 +534,7 @@ class AdminHotelRoomsBookingController extends ModuleAdminController $start_date = date('Y-m-d', strtotime('+1 day', strtotime($start_date))); } if ($booking_calendar_data) { - die(Tools::jsonEncode($booking_calendar_data)); + die(json_encode($booking_calendar_data)); } else { die(0); } diff --git a/modules/hotelreservationsystem/define.php b/modules/hotelreservationsystem/define.php index cffdcab88..71fdba434 100644 --- a/modules/hotelreservationsystem/define.php +++ b/modules/hotelreservationsystem/define.php @@ -25,7 +25,6 @@ require_once 'classes/HotelImage.php'; require_once 'classes/HotelFeatures.php'; require_once 'classes/HotelBranchFeatures.php'; require_once 'classes/HotelRoomStatus.php'; -require_once 'classes/HotelOrderStatus.php'; require_once 'classes/HotelRoomAllotmentType.php'; require_once 'classes/HotelBookingDetail.php'; require_once 'classes/HotelCartBookingData.php'; diff --git a/modules/hotelreservationsystem/hotelreservationsystem.php b/modules/hotelreservationsystem/hotelreservationsystem.php index 5b285e12a..462a50b9d 100644 --- a/modules/hotelreservationsystem/hotelreservationsystem.php +++ b/modules/hotelreservationsystem/hotelreservationsystem.php @@ -299,7 +299,7 @@ class hotelreservationsystem extends Module if (Validate::isLoadedObject( $objCartBooking = new HotelCartBookingData($demandInfo['id']) )) { - $objCartBooking->extra_demands = Tools::jsonEncode($demandInfo['extra_demands']); + $objCartBooking->extra_demands = json_encode($demandInfo['extra_demands']); $objCartBooking->save(); } } @@ -443,7 +443,7 @@ class hotelreservationsystem extends Module if ($objHtlBkDtl->save()) { // save extra demands info if ($objCartBkData->extra_demands - && ($extraDemands = Tools::jsonDecode($objCartBkData->extra_demands, true)) + && ($extraDemands = json_decode($objCartBkData->extra_demands, true)) ) { $objRoomDemandPrice = new HotelRoomTypeDemandPrice(); foreach ($extraDemands as $demand) { @@ -669,7 +669,6 @@ class hotelreservationsystem extends Module || !$this->registerModuleHooks() || !$objHtlHelper->insertDefaultHotelEntries() || !$objHtlHelper->insertHotelRoomsStatus() - || !$objHtlHelper->insertHotelOrderStatus() || !$objHtlHelper->insertHotelRoomAllotmentType() ) { return false; @@ -739,8 +738,7 @@ class hotelreservationsystem extends Module `'._DB_PREFIX_.'htl_room_type_demand_price`, `'._DB_PREFIX_.'htl_room_type_demand`, `'._DB_PREFIX_.'htl_room_disable_dates`, - `'._DB_PREFIX_.'htl_access`, - `'._DB_PREFIX_.'htl_order_status`,' + `'._DB_PREFIX_.'htl_access`' ); } diff --git a/modules/hotelreservationsystem/install.sql b/modules/hotelreservationsystem/install.sql index ab70d7f10..2f5e6ac07 100644 --- a/modules/hotelreservationsystem/install.sql +++ b/modules/hotelreservationsystem/install.sql @@ -361,9 +361,3 @@ CREATE TABLE IF NOT EXISTS `PREFIX_htl_access` ( `access` int(11) NOT NULL, PRIMARY KEY (`id_profile`, `id_hotel`) ) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8; - -CREATE TABLE IF NOT EXISTS `PREFIX_htl_order_status` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `status` text NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; diff --git a/modules/paypal/api/ApiPaypalPlus.php b/modules/paypal/api/ApiPaypalPlus.php index 21550cdea..56fd693b7 100644 --- a/modules/paypal/api/ApiPaypalPlus.php +++ b/modules/paypal/api/ApiPaypalPlus.php @@ -99,7 +99,7 @@ class ApiPaypalPlus /* * Init variable */ - $oPayPalToken = Tools::jsonDecode($result); + $oPayPalToken = json_decode($result); if (isset($oPayPalToken->error)) { return false; @@ -159,7 +159,7 @@ class ApiPaypalPlus 'Authorization:Bearer '.$accessToken, ); - $result = Tools::jsonDecode($this->sendByCURL(URL_PPP_WEBPROFILE, Tools::jsonEncode($data), $header)); + $result = json_decode($this->sendByCURL(URL_PPP_WEBPROFILE, json_encode($data), $header)); if (isset($result->id)) { return $result->id; } else { @@ -189,7 +189,7 @@ class ApiPaypalPlus 'Authorization:Bearer '.$accessToken, ); - return Tools::jsonDecode($this->sendByCURL(URL_PPP_WEBPROFILE, false, $header)); + return json_decode($this->sendByCURL(URL_PPP_WEBPROFILE, false, $header)); } } @@ -358,7 +358,7 @@ class ApiPaypalPlus 'Authorization:Bearer '.$access_token, ); - $result = $this->sendByCURL(URL_PPP_CREATE_PAYMENT, Tools::jsonEncode($data), $header); + $result = $this->sendByCURL(URL_PPP_CREATE_PAYMENT, json_encode($data), $header); return $result; } diff --git a/modules/paypal/api/CallApiPaypalPlus.php b/modules/paypal/api/CallApiPaypalPlus.php index 22fce69d8..80444cb9e 100644 --- a/modules/paypal/api/CallApiPaypalPlus.php +++ b/modules/paypal/api/CallApiPaypalPlus.php @@ -57,7 +57,7 @@ class CallApiPaypalPlus extends ApiPaypalPlus if ($accessToken != false) { - $result = Tools::jsonDecode($this->createPayment($this->customer, $this->cart, $accessToken)); + $result = json_decode($this->createPayment($this->customer, $this->cart, $accessToken)); if (isset($result->links)) { @@ -105,7 +105,7 @@ class CallApiPaypalPlus extends ApiPaypalPlus ); $data = array('payer_id' => $payer_id); - $response = $this->sendByCURL(URL_PPP_EXECUTE_PAYMENT.$paymentId.'/execute/', Tools::jsonEncode($data), $header); + $response = $this->sendByCURL(URL_PPP_EXECUTE_PAYMENT.$paymentId.'/execute/', json_encode($data), $header); return $response; } @@ -124,7 +124,7 @@ class CallApiPaypalPlus extends ApiPaypalPlus 'Authorization:Bearer '.$accessToken, ); - return $this->sendByCURL(URL_PPP_EXECUTE_REFUND.$paymentId.'/refund', Tools::jsonEncode($data), $header); + return $this->sendByCURL(URL_PPP_EXECUTE_REFUND.$paymentId.'/refund', json_encode($data), $header); } public function patch($id_payment, $address) @@ -203,7 +203,7 @@ class CallApiPaypalPlus extends ApiPaypalPlus 'Content-Type:application/json', 'Authorization:Bearer '.$accessToken, ); - $body = str_replace('\/transactions\/0\/item_list\/shipping_address', '/transactions/0/item_list/shipping_address', Tools::jsonEncode($payment)); + $body = str_replace('\/transactions\/0\/item_list\/shipping_address', '/transactions/0/item_list/shipping_address', json_encode($payment)); return $this->sendByCURL(URL_PPP_PATCH.$id_payment, $body, $header, false, 'PATCH'); } } diff --git a/modules/paypal/api/sdk/braintree/lib/Braintree/Digest.php b/modules/paypal/api/sdk/braintree/lib/Braintree/Digest.php index ec6d9e090..c859c61b2 100644 --- a/modules/paypal/api/sdk/braintree/lib/Braintree/Digest.php +++ b/modules/paypal/api/sdk/braintree/lib/Braintree/Digest.php @@ -52,8 +52,8 @@ class Digest $outerPad = str_repeat(chr(0x5C), 64); for ($i = 0; $i < 20; $i++) { - $innerPad{$i} = $keyDigest{$i} ^ $innerPad{$i}; - $outerPad{$i} = $keyDigest{$i} ^ $outerPad{$i}; + $innerPad[$i] = $keyDigest[$i] ^ $innerPad[$i]; + $outerPad[$i] = $keyDigest[$i] ^ $outerPad[$i]; } return sha1($outerPad.pack($pack, sha1($innerPad.$message))); diff --git a/modules/paypal/api/sdk/braintree/lib/Braintree/Util.php b/modules/paypal/api/sdk/braintree/lib/Braintree/Util.php index 23d4af6bf..0a7757ce5 100644 --- a/modules/paypal/api/sdk/braintree/lib/Braintree/Util.php +++ b/modules/paypal/api/sdk/braintree/lib/Braintree/Util.php @@ -202,7 +202,7 @@ class Util // every time this function is called. static $callback = null; if ($callback === null) { - $callback = create_function('$matches', 'return strtoupper($matches[1]);'); + $callback = function ($matches) { return strtoupper($matches[1]); }; } return preg_replace_callback('/' . $delimiter . '(\w)/', $callback, $string); diff --git a/modules/paypal/classes/Braintree.php b/modules/paypal/classes/Braintree.php index f62147ed7..4f24350f2 100644 --- a/modules/paypal/classes/Braintree.php +++ b/modules/paypal/classes/Braintree.php @@ -306,7 +306,7 @@ class PrestaBraintree curl_close($ch); - $json = Tools::jsonDecode($resp); + $json = json_decode($resp); Configuration::updateValue('PAYPAL_BRAINTREE_ACCESS_TOKEN', $json->data->accessToken); Configuration::updateValue('PAYPAL_BRAINTREE_REFRESH_TOKEN', $json->data->refreshToken); diff --git a/modules/paypal/controllers/front/submitplus.php b/modules/paypal/controllers/front/submitplus.php index 78b360932..2b6fcab58 100644 --- a/modules/paypal/controllers/front/submitplus.php +++ b/modules/paypal/controllers/front/submitplus.php @@ -68,7 +68,7 @@ class PayPalSubmitplusModuleFrontController extends ModuleFrontController if (!empty($this->id_cart) && !empty($this->paymentId) && !empty($this->token)) { $CallApiPaypalPlus = new CallApiPaypalPlus(); - $payment = Tools::jsonDecode($CallApiPaypalPlus->lookUpPayment($this->paymentId)); + $payment = json_decode($CallApiPaypalPlus->lookUpPayment($this->paymentId)); if (isset($payment->state)) { $this->context->smarty->assign('state', $payment->state); @@ -172,7 +172,7 @@ class PayPalSubmitplusModuleFrontController extends ModuleFrontController $return = array(); if (!$ajax) { $return['error'][] = $this->module->l('An error occured during the payment'); - echo Tools::jsonEncode($return); + echo json_encode($return); die(); } @@ -187,7 +187,7 @@ class PayPalSubmitplusModuleFrontController extends ModuleFrontController && !empty($submit) ) { $CallApiPaypalPlus = new CallApiPaypalPlus(); - $payment = Tools::jsonDecode($CallApiPaypalPlus->executePayment($payerID, $paymentId)); + $payment = json_decode($CallApiPaypalPlus->executePayment($payerID, $paymentId)); if (isset($payment->state)) { @@ -230,7 +230,7 @@ class PayPalSubmitplusModuleFrontController extends ModuleFrontController $paypal_plus_pui = new PaypalPlusPui(); $paypal_plus_pui->id_order = $id_order; - $paypal_plus_pui->pui_informations = Tools::jsonEncode($payment->payment_instruction); + $paypal_plus_pui->pui_informations = json_encode($payment->payment_instruction); $paypal_plus_pui->save(); } @@ -254,7 +254,7 @@ class PayPalSubmitplusModuleFrontController extends ModuleFrontController $return['error'][] = $this->module->l('An error occured during the payment'); } - echo Tools::jsonEncode($return); + echo json_encode($return); die(); } diff --git a/modules/paypal/integral_evolution/notifier.php b/modules/paypal/integral_evolution/notifier.php index be2f95eab..24b32f21f 100644 --- a/modules/paypal/integral_evolution/notifier.php +++ b/modules/paypal/integral_evolution/notifier.php @@ -108,6 +108,6 @@ class PayPalNotifier extends PayPal if ($custom = Tools::getValue('custom')) { $notifier = new PayPalNotifier(); - $result = Tools::jsonDecode($custom, true); + $result = json_decode($custom, true); $notifier->confirmOrder($result); } diff --git a/modules/paypal/ipn.php b/modules/paypal/ipn.php index 55cb90d4b..20f1282ae 100644 --- a/modules/paypal/ipn.php +++ b/modules/paypal/ipn.php @@ -148,7 +148,7 @@ class PayPalIPN extends PayPal $cart_details = Context::getContext()->cart->getSummaryDetails(null, true); $cart_hash = sha1(serialize(Context::getContext()->cart->nbProducts())); - $custom = Tools::jsonDecode(Tools::getValue('custom'), true); + $custom = json_decode(Tools::getValue('custom'), true); $shipping = $cart_details['total_shipping_tax_exc']; $subtotal = $cart_details['total_price_without_tax'] - $cart_details['total_shipping_tax_exc']; @@ -234,7 +234,7 @@ if (Tools::getValue('receiver_email') == Configuration::get('PAYPAL_BUSINESS_ACC if (Tools::getIsset('custom')) { $ipn = new PayPalIPN(); - $custom = Tools::jsonDecode(Tools::getValue('custom'), true); + $custom = json_decode(Tools::getValue('custom'), true); $ipn->confirmOrder($custom); } } diff --git a/modules/paypal/paypal.php b/modules/paypal/paypal.php index 67f1c3c06..b79adf57a 100644 --- a/modules/paypal/paypal.php +++ b/modules/paypal/paypal.php @@ -699,7 +699,7 @@ class PayPal extends PaymentModule //'PayPal_version_tls_checked' => $tls_version, 'Presta_version' => _PS_VERSION_, 'Currencies' => Currency::getCurrencies(), - 'PayPal_account_braintree' => (array) Tools::jsonDecode(Configuration::get('PAYPAL_ACCOUNT_BRAINTREE')), + 'PayPal_account_braintree' => (array) json_decode(Configuration::get('PAYPAL_ACCOUNT_BRAINTREE')), 'Currency_default'=> Configuration::get('PS_CURRENCY_DEFAULT'), //*TO DELETE* 'PayPal_braintree_public_key'=> Configuration::get('PAYPAL_BRAINTREE_PUBLIC_KEY'), //*TO DELETE* 'PayPal_braintree_private_key'=> Configuration::get('PAYPAL_BRAINTREE_PRIVATE_KEY'), @@ -1070,7 +1070,7 @@ class PayPal extends PaymentModule 'currency' => new Currency((int) $cart->id_currency), 'customer' => $this->context->customer, 'business_account' => Configuration::get('PAYPAL_BUSINESS_ACCOUNT'), - 'custom' => Tools::jsonEncode(array('id_cart' => $cart->id, 'hash' => sha1(serialize($cart->nbProducts())))), + 'custom' => json_encode(array('id_cart' => $cart->id, 'hash' => sha1(serialize($cart->nbProducts())))), 'gift_price' => (float) $this->getGiftWrappingPrice(), 'billing_address' => $billing_address, 'delivery_address' => $delivery_address, @@ -1879,7 +1879,7 @@ class PayPal extends PaymentModule } $account_brain = Tools::getValue('account_braintree'); - Configuration::updateValue('PAYPAL_ACCOUNT_BRAINTREE', Tools::jsonEncode($account_brain)); + Configuration::updateValue('PAYPAL_ACCOUNT_BRAINTREE', json_encode($account_brain)); $this->context->smarty->assign('PayPal_save_success', true); @@ -1985,7 +1985,7 @@ class PayPal extends PaymentModule $callApiPaypalPlus = new CallApiPaypalPlus(); - return Tools::jsonDecode($callApiPaypalPlus->executeRefund($id_transaction, $params)); + return json_decode($callApiPaypalPlus->executeRefund($id_transaction, $params)); } } @@ -2052,7 +2052,7 @@ class PayPal extends PaymentModule $message = $this->l('Refund operation result:')." \r\n"; foreach ($response as $key => $value) { if (is_object($value) || is_array($value)) { - $message .= $key.': '.Tools::jsonEncode($value)." \r\n"; + $message .= $key.': '.json_encode($value)." \r\n"; } else { $message .= $key.': '.$value." \r\n"; } @@ -2550,9 +2550,9 @@ class PayPal extends PaymentModule // check digit-by-digit, if they have a difference, return 1 or -1 (greater/lower than) for ($i = 0; $i < Tools::strlen($num1); $i++) { - if ((int) $num1{$i} > (int) $num2{$i}) { + if ((int) $num1[$i] > (int) $num2[$i]) { return 1; - } elseif ((int) $num1{$i} < (int) $num2{$i}) { + } elseif ((int) $num1[$i] < (int) $num2[$i]) { return -1; } @@ -2575,7 +2575,7 @@ class PayPal extends PaymentModule 'address_billing' => new Address($this->context->cart->id_address_invoice), 'cart' => $this->context->cart, 'patternRules' => array('avoid' => array()), - 'cart_image_size' => version_compare(_PS_VERSION_, '1.5', '<') ? 'small' : version_compare(_PS_VERSION_, '1.6', '<') ? 'small_default' : 'cart_default', + 'cart_image_size' => version_compare(_PS_VERSION_, '1.5', '<') ? 'small' : (version_compare(_PS_VERSION_, '1.6', '<') ? 'small_default' : 'cart_default'), 'useStyle14' => version_compare(_PS_VERSION_, '1.5', '<'), 'useStyle15' => version_compare(_PS_VERSION_, '1.5', '>') && version_compare(_PS_VERSION_, '1.6', '<'), )); @@ -2587,7 +2587,7 @@ class PayPal extends PaymentModule public function set_good_context() { - $account_braintree = Tools::jsonDecode(Configuration::get('PAYPAL_ACCOUNT_BRAINTREE'), true); + $account_braintree = json_decode(Configuration::get('PAYPAL_ACCOUNT_BRAINTREE'), true); $currency = new Currency($this->context->cart->id_currency); $this->context_modified = false; $this->id_currency_origin_cart = $this->context->cart->id_currency; @@ -2616,7 +2616,7 @@ class PayPal extends PaymentModule if (Validate::isLoadedObject($order = new Order($params['object']->id_order))) { if ($order->module == $this->name) { $order_detail = PaypalPlusPui::getByIdOrder($params['object']->id_order); - $information = Tools::jsonDecode($order_detail['pui_informations'], true); + $information = json_decode($order_detail['pui_informations'], true); $tab = ' diff --git a/modules/paypal/paypal_login/paypal_login.php b/modules/paypal/paypal_login/paypal_login.php index c497066dc..3e14d73be 100644 --- a/modules/paypal/paypal_login/paypal_login.php +++ b/modules/paypal/paypal_login/paypal_login.php @@ -103,7 +103,7 @@ class PayPalLogin fclose($handle); }*/ - $result = Tools::jsonDecode($result); + $result = json_decode($result); if ($result) { @@ -161,7 +161,7 @@ class PayPalLogin } */ - $result = Tools::jsonDecode($result); + $result = json_decode($result); if ($result) { $login->access_token = $result->access_token; @@ -199,7 +199,7 @@ class PayPalLogin } */ - $result = Tools::jsonDecode($result); + $result = json_decode($result); if ($result) { $customer = new Customer(); diff --git a/modules/paypal/paypal_plus/submit.php b/modules/paypal/paypal_plus/submit.php index edd6e6cfe..c0a231522 100644 --- a/modules/paypal/paypal_plus/submit.php +++ b/modules/paypal/paypal_plus/submit.php @@ -70,7 +70,7 @@ function displayConfirm($context) if (!empty($id_cart) && !empty($paymentId) && !empty($token)) { $CallApiPaypalPlus = new CallApiPaypalPlus(); - $payment = Tools::jsonDecode($CallApiPaypalPlus->lookUpPayment($paymentId)); + $payment = json_decode($CallApiPaypalPlus->lookUpPayment($paymentId)); if (isset($payment->state)) { $context->smarty->assign('state', $payment->state); @@ -158,7 +158,7 @@ function displayAjax($context) include_once _PS_MODULE_DIR_.'paypal/paypal.php'; $CallApiPaypalPlus = new CallApiPaypalPlus(); - $payment = Tools::jsonDecode($CallApiPaypalPlus->executePayment($payerID, $paymentId)); + $payment = json_decode($CallApiPaypalPlus->executePayment($payerID, $paymentId)); if (isset($payment->state)) { $transaction = array( @@ -198,7 +198,7 @@ function displayAjax($context) $order = Order::getOrderByCartId($id_cart); $paypal_plus_pui = new PaypalPlusPui(); $paypal_plus_pui->id_order = $order->id; - $paypal_plus_pui->pui_informations = Tools::jsonEncode($payment->payment_instruction); + $paypal_plus_pui->pui_informations = json_encode($payment->payment_instruction); } } elseif ($submit == 'confirmCancel') { $paypal->validateOrder( @@ -220,7 +220,7 @@ function displayAjax($context) $return['error'][] = $paypal->l('An error occured during the payment'); } - echo Tools::jsonEncode($return); + echo json_encode($return); die(); } diff --git a/modules/productcomments/controllers/front/default.php b/modules/productcomments/controllers/front/default.php index 2f7196bcb..e53694ed3 100644 --- a/modules/productcomments/controllers/front/default.php +++ b/modules/productcomments/controllers/front/default.php @@ -144,7 +144,7 @@ class ProductCommentsDefaultModuleFrontController extends ModuleFrontController else $result = false; - die(Tools::jsonEncode(array( + die(json_encode(array( 'result' => $result, 'errors' => $errors ))); diff --git a/modules/productcomments/productcomments-ajax.php b/modules/productcomments/productcomments-ajax.php index 770d261cc..f3ec718f3 100644 --- a/modules/productcomments/productcomments-ajax.php +++ b/modules/productcomments/productcomments-ajax.php @@ -52,7 +52,7 @@ if (Tools::getValue('action') && Tools::getValue('id_product_comment') && Contex } else if (Tools::getValue('action') && Tools::getValue('secure_key') == $productCom->secure_key) { - $review = Tools::jsonDecode(Tools::getValue('review')); + $review = json_decode(Tools::getValue('review')); $id_product = 0; $content = null; $title = null; diff --git a/modules/sekeywords/sekeywords.php b/modules/sekeywords/sekeywords.php index 0e7cd850a..b259a3961 100644 --- a/modules/sekeywords/sekeywords.php +++ b/modules/sekeywords/sekeywords.php @@ -89,7 +89,7 @@ class SEKeywords extends ModuleGraph public function hookTop($params) { - if (!isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], Tools::getHttpHost(false, false) == 0)) { + if (!isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], Tools::getHttpHost(false, false)) == 0) { return; } diff --git a/modules/sendtoafriend/sendtoafriend_ajax.php b/modules/sendtoafriend/sendtoafriend_ajax.php index cccceef4d..97843d855 100644 --- a/modules/sendtoafriend/sendtoafriend_ajax.php +++ b/modules/sendtoafriend/sendtoafriend_ajax.php @@ -35,7 +35,7 @@ if (Module::isEnabled('sendtoafriend') && Tools::getValue('action') == 'sendToMy // Retrocompatibilty with old theme if($friend = Tools::getValue('friend')) { - $friend = Tools::jsonDecode($friend, true); + $friend = json_decode($friend, true); foreach ($friend as $key => $value) { diff --git a/modules/wkroomsearchblock/controllers/front/autocompletesearch.php b/modules/wkroomsearchblock/controllers/front/autocompletesearch.php index f9770446e..d8aa6ad59 100644 --- a/modules/wkroomsearchblock/controllers/front/autocompletesearch.php +++ b/modules/wkroomsearchblock/controllers/front/autocompletesearch.php @@ -60,6 +60,6 @@ class WkRoomSearchBlockAutoCompleteSearchModuleFrontController extends ModuleFro } else { $result['status'] = 'failed3'; } - die(Tools::jsonEncode($result)); + die(json_encode($result)); } } diff --git a/pdf/invoice.product-tab.tpl b/pdf/invoice.product-tab.tpl index 62ef53264..dc75ea09c 100644 --- a/pdf/invoice.product-tab.tpl +++ b/pdf/invoice.product-tab.tpl @@ -84,12 +84,12 @@ s with a . + + $ws_accum =& $initial_ws; + + foreach ($children as $node) { + if ($node instanceof HTMLPurifier_Node_Comment) { + $ws_accum[] = $node; + continue; + } + switch ($node->name) { + case 'tbody': + $tbody_mode = true; + // fall through + case 'tr': + $content[] = $node; + $ws_accum =& $content; + break; + case 'caption': + // there can only be one caption! + if ($caption !== false) break; + $caption = $node; + $ws_accum =& $after_caption_ws; + break; + case 'thead': + $tbody_mode = true; + // XXX This breaks rendering properties with + // Firefox, which never floats a to + // the top. Ever. (Our scheme will float the + // first to the top.) So maybe + // s that are not first should be + // turned into ? Very tricky, indeed. + if ($thead === false) { + $thead = $node; + $ws_accum =& $after_thead_ws; + } else { + // Oops, there's a second one! What + // should we do? Current behavior is to + // transmutate the first and last entries into + // tbody tags, and then put into content. + // Maybe a better idea is to *attach + // it* to the existing thead or tfoot? + // We don't do this, because Firefox + // doesn't float an extra tfoot to the + // bottom like it does for the first one. + $node->name = 'tbody'; + $content[] = $node; + $ws_accum =& $content; + } + break; + case 'tfoot': + // see above for some aveats + $tbody_mode = true; + if ($tfoot === false) { + $tfoot = $node; + $ws_accum =& $after_tfoot_ws; + } else { + $node->name = 'tbody'; + $content[] = $node; + $ws_accum =& $content; + } + break; + case 'colgroup': + case 'col': + $cols[] = $node; + $ws_accum =& $cols; + break; + case '#PCDATA': + // How is whitespace handled? We treat is as sticky to + // the *end* of the previous element. So all of the + // nonsense we have worked on is to keep things + // together. + if (!empty($node->is_whitespace)) { + $ws_accum[] = $node; + } + break; + } + } + + if (empty($content)) { + return false; + } + + $ret = $initial_ws; + if ($caption !== false) { + $ret[] = $caption; + $ret = array_merge($ret, $after_caption_ws); + } + if ($cols !== false) { + $ret = array_merge($ret, $cols); + } + if ($thead !== false) { + $ret[] = $thead; + $ret = array_merge($ret, $after_thead_ws); + } + if ($tfoot !== false) { + $ret[] = $tfoot; + $ret = array_merge($ret, $after_tfoot_ws); + } + + if ($tbody_mode) { + // we have to shuffle tr into tbody + $current_tr_tbody = null; + + foreach($content as $node) { + switch ($node->name) { + case 'tbody': + $current_tr_tbody = null; + $ret[] = $node; + break; + case 'tr': + if ($current_tr_tbody === null) { + $current_tr_tbody = new HTMLPurifier_Node_Element('tbody'); + $ret[] = $current_tr_tbody; + } + $current_tr_tbody->children[] = $node; + break; + case '#PCDATA': + //assert($node->is_whitespace); + if ($current_tr_tbody === null) { + $ret[] = $node; + } else { + $current_tr_tbody->children[] = $node; + } + break; + } + } + } else { + $ret = array_merge($ret, $content); + } + + return $ret; + + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ChildDef/index.php b/tools/htmlpurifier/HTMLPurifier/ChildDef/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ChildDef/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/HTMLPurifier/Config.php b/tools/htmlpurifier/HTMLPurifier/Config.php new file mode 100644 index 000000000..3133d8a4f --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/Config.php @@ -0,0 +1,920 @@ +defaultPlist; + $this->plist = new HTMLPurifier_PropertyList($parent); + $this->def = $definition; // keep a copy around for checking + $this->parser = new HTMLPurifier_VarParser_Flexible(); + } + + /** + * Convenience constructor that creates a config object based on a mixed var + * @param mixed $config Variable that defines the state of the config + * object. Can be: a HTMLPurifier_Config() object, + * an array of directives based on loadArray(), + * or a string filename of an ini file. + * @param HTMLPurifier_ConfigSchema $schema Schema object + * @return HTMLPurifier_Config Configured object + */ + public static function create($config, $schema = null) + { + if ($config instanceof HTMLPurifier_Config) { + // pass-through + return $config; + } + if (!$schema) { + $ret = HTMLPurifier_Config::createDefault(); + } else { + $ret = new HTMLPurifier_Config($schema); + } + if (is_string($config)) { + $ret->loadIni($config); + } elseif (is_array($config)) $ret->loadArray($config); + return $ret; + } + + /** + * Creates a new config object that inherits from a previous one. + * @param HTMLPurifier_Config $config Configuration object to inherit from. + * @return HTMLPurifier_Config object with $config as its parent. + */ + public static function inherit(HTMLPurifier_Config $config) + { + return new HTMLPurifier_Config($config->def, $config->plist); + } + + /** + * Convenience constructor that creates a default configuration object. + * @return HTMLPurifier_Config default object. + */ + public static function createDefault() + { + $definition = HTMLPurifier_ConfigSchema::instance(); + $config = new HTMLPurifier_Config($definition); + return $config; + } + + /** + * Retrieves a value from the configuration. + * + * @param string $key String key + * @param mixed $a + * + * @return mixed + */ + public function get($key, $a = null) + { + if ($a !== null) { + $this->triggerError( + "Using deprecated API: use \$config->get('$key.$a') instead", + E_USER_WARNING + ); + $key = "$key.$a"; + } + if (!$this->finalized) { + $this->autoFinalize(); + } + if (!isset($this->def->info[$key])) { + // can't add % due to SimpleTest bug + $this->triggerError( + 'Cannot retrieve value of undefined directive ' . htmlspecialchars($key), + E_USER_WARNING + ); + return; + } + if (isset($this->def->info[$key]->isAlias)) { + $d = $this->def->info[$key]; + $this->triggerError( + 'Cannot get value from aliased directive, use real name ' . $d->key, + E_USER_ERROR + ); + return; + } + if ($this->lock) { + list($ns) = explode('.', $key); + if ($ns !== $this->lock) { + $this->triggerError( + 'Cannot get value of namespace ' . $ns . ' when lock for ' . + $this->lock . + ' is active, this probably indicates a Definition setup method ' . + 'is accessing directives that are not within its namespace', + E_USER_ERROR + ); + return; + } + } + return $this->plist->get($key); + } + + /** + * Retrieves an array of directives to values from a given namespace + * + * @param string $namespace String namespace + * + * @return array + */ + public function getBatch($namespace) + { + if (!$this->finalized) { + $this->autoFinalize(); + } + $full = $this->getAll(); + if (!isset($full[$namespace])) { + $this->triggerError( + 'Cannot retrieve undefined namespace ' . + htmlspecialchars($namespace), + E_USER_WARNING + ); + return; + } + return $full[$namespace]; + } + + /** + * Returns a SHA-1 signature of a segment of the configuration object + * that uniquely identifies that particular configuration + * + * @param string $namespace Namespace to get serial for + * + * @return string + * @note Revision is handled specially and is removed from the batch + * before processing! + */ + public function getBatchSerial($namespace) + { + if (empty($this->serials[$namespace])) { + $batch = $this->getBatch($namespace); + unset($batch['DefinitionRev']); + $this->serials[$namespace] = sha1(serialize($batch)); + } + return $this->serials[$namespace]; + } + + /** + * Returns a SHA-1 signature for the entire configuration object + * that uniquely identifies that particular configuration + * + * @return string + */ + public function getSerial() + { + if (empty($this->serial)) { + $this->serial = sha1(serialize($this->getAll())); + } + return $this->serial; + } + + /** + * Retrieves all directives, organized by namespace + * + * @warning This is a pretty inefficient function, avoid if you can + */ + public function getAll() + { + if (!$this->finalized) { + $this->autoFinalize(); + } + $ret = array(); + foreach ($this->plist->squash() as $name => $value) { + list($ns, $key) = explode('.', $name, 2); + $ret[$ns][$key] = $value; + } + return $ret; + } + + /** + * Sets a value to configuration. + * + * @param string $key key + * @param mixed $value value + * @param mixed $a + */ + public function set($key, $value, $a = null) + { + if (strpos($key, '.') === false) { + $namespace = $key; + $directive = $value; + $value = $a; + $key = "$key.$directive"; + $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE); + } else { + list($namespace) = explode('.', $key); + } + if ($this->isFinalized('Cannot set directive after finalization')) { + return; + } + if (!isset($this->def->info[$key])) { + $this->triggerError( + 'Cannot set undefined directive ' . htmlspecialchars($key) . ' to value', + E_USER_WARNING + ); + return; + } + $def = $this->def->info[$key]; + + if (isset($def->isAlias)) { + if ($this->aliasMode) { + $this->triggerError( + 'Double-aliases not allowed, please fix '. + 'ConfigSchema bug with' . $key, + E_USER_ERROR + ); + return; + } + $this->aliasMode = true; + $this->set($def->key, $value); + $this->aliasMode = false; + $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE); + return; + } + + // Raw type might be negative when using the fully optimized form + // of stdClass, which indicates allow_null == true + $rtype = is_int($def) ? $def : $def->type; + if ($rtype < 0) { + $type = -$rtype; + $allow_null = true; + } else { + $type = $rtype; + $allow_null = isset($def->allow_null); + } + + try { + $value = $this->parser->parse($value, $type, $allow_null); + } catch (HTMLPurifier_VarParserException $e) { + $this->triggerError( + 'Value for ' . $key . ' is of invalid type, should be ' . + HTMLPurifier_VarParser::getTypeName($type), + E_USER_WARNING + ); + return; + } + if (is_string($value) && is_object($def)) { + // resolve value alias if defined + if (isset($def->aliases[$value])) { + $value = $def->aliases[$value]; + } + // check to see if the value is allowed + if (isset($def->allowed) && !isset($def->allowed[$value])) { + $this->triggerError( + 'Value not supported, valid values are: ' . + $this->_listify($def->allowed), + E_USER_WARNING + ); + return; + } + } + $this->plist->set($key, $value); + + // reset definitions if the directives they depend on changed + // this is a very costly process, so it's discouraged + // with finalization + if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') { + $this->definitions[$namespace] = null; + } + + $this->serials[$namespace] = false; + } + + /** + * Convenience function for error reporting + * + * @param array $lookup + * + * @return string + */ + private function _listify($lookup) + { + $list = array(); + foreach ($lookup as $name => $b) { + $list[] = $name; + } + return implode(', ', $list); + } + + /** + * Retrieves object reference to the HTML definition. + * + * @param bool $raw Return a copy that has not been setup yet. Must be + * called before it's been setup, otherwise won't work. + * @param bool $optimized If true, this method may return null, to + * indicate that a cached version of the modified + * definition object is available and no further edits + * are necessary. Consider using + * maybeGetRawHTMLDefinition, which is more explicitly + * named, instead. + * + * @return HTMLPurifier_HTMLDefinition|null + */ + public function getHTMLDefinition($raw = false, $optimized = false) + { + return $this->getDefinition('HTML', $raw, $optimized); + } + + /** + * Retrieves object reference to the CSS definition + * + * @param bool $raw Return a copy that has not been setup yet. Must be + * called before it's been setup, otherwise won't work. + * @param bool $optimized If true, this method may return null, to + * indicate that a cached version of the modified + * definition object is available and no further edits + * are necessary. Consider using + * maybeGetRawCSSDefinition, which is more explicitly + * named, instead. + * + * @return HTMLPurifier_CSSDefinition|null + */ + public function getCSSDefinition($raw = false, $optimized = false) + { + return $this->getDefinition('CSS', $raw, $optimized); + } + + /** + * Retrieves object reference to the URI definition + * + * @param bool $raw Return a copy that has not been setup yet. Must be + * called before it's been setup, otherwise won't work. + * @param bool $optimized If true, this method may return null, to + * indicate that a cached version of the modified + * definition object is available and no further edits + * are necessary. Consider using + * maybeGetRawURIDefinition, which is more explicitly + * named, instead. + * + * @return HTMLPurifier_URIDefinition|null + */ + public function getURIDefinition($raw = false, $optimized = false) + { + return $this->getDefinition('URI', $raw, $optimized); + } + + /** + * Retrieves a definition + * + * @param string $type Type of definition: HTML, CSS, etc + * @param bool $raw Whether or not definition should be returned raw + * @param bool $optimized Only has an effect when $raw is true. Whether + * or not to return null if the result is already present in + * the cache. This is off by default for backwards + * compatibility reasons, but you need to do things this + * way in order to ensure that caching is done properly. + * Check out enduser-customize.html for more details. + * We probably won't ever change this default, as much as the + * maybe semantics is the "right thing to do." + * + * @throws HTMLPurifier_Exception + * @return HTMLPurifier_Definition|null + */ + public function getDefinition($type, $raw = false, $optimized = false) + { + if ($optimized && !$raw) { + throw new HTMLPurifier_Exception("Cannot set optimized = true when raw = false"); + } + if (!$this->finalized) { + $this->autoFinalize(); + } + // temporarily suspend locks, so we can handle recursive definition calls + $lock = $this->lock; + $this->lock = null; + $factory = HTMLPurifier_DefinitionCacheFactory::instance(); + $cache = $factory->create($type, $this); + $this->lock = $lock; + if (!$raw) { + // full definition + // --------------- + // check if definition is in memory + if (!empty($this->definitions[$type])) { + $def = $this->definitions[$type]; + // check if the definition is setup + if ($def->setup) { + return $def; + } else { + $def->setup($this); + if ($def->optimized) { + $cache->add($def, $this); + } + return $def; + } + } + // check if definition is in cache + $def = $cache->get($this); + if ($def) { + // definition in cache, save to memory and return it + $this->definitions[$type] = $def; + return $def; + } + // initialize it + $def = $this->initDefinition($type); + // set it up + $this->lock = $type; + $def->setup($this); + $this->lock = null; + // save in cache + $cache->add($def, $this); + // return it + return $def; + } else { + // raw definition + // -------------- + // check preconditions + $def = null; + if ($optimized) { + if (is_null($this->get($type . '.DefinitionID'))) { + // fatally error out if definition ID not set + throw new HTMLPurifier_Exception( + "Cannot retrieve raw version without specifying %$type.DefinitionID" + ); + } + } + if (!empty($this->definitions[$type])) { + $def = $this->definitions[$type]; + if ($def->setup && !$optimized) { + $extra = $this->chatty ? + " (try moving this code block earlier in your initialization)" : + ""; + throw new HTMLPurifier_Exception( + "Cannot retrieve raw definition after it has already been setup" . + $extra + ); + } + if ($def->optimized === null) { + $extra = $this->chatty ? " (try flushing your cache)" : ""; + throw new HTMLPurifier_Exception( + "Optimization status of definition is unknown" . $extra + ); + } + if ($def->optimized !== $optimized) { + $msg = $optimized ? "optimized" : "unoptimized"; + $extra = $this->chatty ? + " (this backtrace is for the first inconsistent call, which was for a $msg raw definition)" + : ""; + throw new HTMLPurifier_Exception( + "Inconsistent use of optimized and unoptimized raw definition retrievals" . $extra + ); + } + } + // check if definition was in memory + if ($def) { + if ($def->setup) { + // invariant: $optimized === true (checked above) + return null; + } else { + return $def; + } + } + // if optimized, check if definition was in cache + // (because we do the memory check first, this formulation + // is prone to cache slamming, but I think + // guaranteeing that either /all/ of the raw + // setup code or /none/ of it is run is more important.) + if ($optimized) { + // This code path only gets run once; once we put + // something in $definitions (which is guaranteed by the + // trailing code), we always short-circuit above. + $def = $cache->get($this); + if ($def) { + // save the full definition for later, but don't + // return it yet + $this->definitions[$type] = $def; + return null; + } + } + // check invariants for creation + if (!$optimized) { + if (!is_null($this->get($type . '.DefinitionID'))) { + if ($this->chatty) { + $this->triggerError( + 'Due to a documentation error in previous version of HTML Purifier, your ' . + 'definitions are not being cached. If this is OK, you can remove the ' . + '%$type.DefinitionRev and %$type.DefinitionID declaration. Otherwise, ' . + 'modify your code to use maybeGetRawDefinition, and test if the returned ' . + 'value is null before making any edits (if it is null, that means that a ' . + 'cached version is available, and no raw operations are necessary). See ' . + '' . + 'Customize for more details', + E_USER_WARNING + ); + } else { + $this->triggerError( + "Useless DefinitionID declaration", + E_USER_WARNING + ); + } + } + } + // initialize it + $def = $this->initDefinition($type); + $def->optimized = $optimized; + return $def; + } + throw new HTMLPurifier_Exception("The impossible happened!"); + } + + /** + * Initialise definition + * + * @param string $type What type of definition to create + * + * @return HTMLPurifier_CSSDefinition|HTMLPurifier_HTMLDefinition|HTMLPurifier_URIDefinition + * @throws HTMLPurifier_Exception + */ + private function initDefinition($type) + { + // quick checks failed, let's create the object + if ($type == 'HTML') { + $def = new HTMLPurifier_HTMLDefinition(); + } elseif ($type == 'CSS') { + $def = new HTMLPurifier_CSSDefinition(); + } elseif ($type == 'URI') { + $def = new HTMLPurifier_URIDefinition(); + } else { + throw new HTMLPurifier_Exception( + "Definition of $type type not supported" + ); + } + $this->definitions[$type] = $def; + return $def; + } + + public function maybeGetRawDefinition($name) + { + return $this->getDefinition($name, true, true); + } + + /** + * @return HTMLPurifier_HTMLDefinition|null + */ + public function maybeGetRawHTMLDefinition() + { + return $this->getDefinition('HTML', true, true); + } + + /** + * @return HTMLPurifier_CSSDefinition|null + */ + public function maybeGetRawCSSDefinition() + { + return $this->getDefinition('CSS', true, true); + } + + /** + * @return HTMLPurifier_URIDefinition|null + */ + public function maybeGetRawURIDefinition() + { + return $this->getDefinition('URI', true, true); + } + + /** + * Loads configuration values from an array with the following structure: + * Namespace.Directive => Value + * + * @param array $config_array Configuration associative array + */ + public function loadArray($config_array) + { + if ($this->isFinalized('Cannot load directives after finalization')) { + return; + } + foreach ($config_array as $key => $value) { + $key = str_replace('_', '.', $key); + if (strpos($key, '.') !== false) { + $this->set($key, $value); + } else { + $namespace = $key; + $namespace_values = $value; + foreach ($namespace_values as $directive => $value2) { + $this->set($namespace .'.'. $directive, $value2); + } + } + } + } + + /** + * Returns a list of array(namespace, directive) for all directives + * that are allowed in a web-form context as per an allowed + * namespaces/directives list. + * + * @param array $allowed List of allowed namespaces/directives + * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy + * + * @return array + */ + public static function getAllowedDirectivesForForm($allowed, $schema = null) + { + if (!$schema) { + $schema = HTMLPurifier_ConfigSchema::instance(); + } + if ($allowed !== true) { + if (is_string($allowed)) { + $allowed = array($allowed); + } + $allowed_ns = array(); + $allowed_directives = array(); + $blacklisted_directives = array(); + foreach ($allowed as $ns_or_directive) { + if (strpos($ns_or_directive, '.') !== false) { + // directive + if ($ns_or_directive[0] == '-') { + $blacklisted_directives[substr($ns_or_directive, 1)] = true; + } else { + $allowed_directives[$ns_or_directive] = true; + } + } else { + // namespace + $allowed_ns[$ns_or_directive] = true; + } + } + } + $ret = array(); + foreach ($schema->info as $key => $def) { + list($ns, $directive) = explode('.', $key, 2); + if ($allowed !== true) { + if (isset($blacklisted_directives["$ns.$directive"])) { + continue; + } + if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) { + continue; + } + } + if (isset($def->isAlias)) { + continue; + } + if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') { + continue; + } + $ret[] = array($ns, $directive); + } + return $ret; + } + + /** + * Loads configuration values from $_GET/$_POST that were posted + * via ConfigForm + * + * @param array $array $_GET or $_POST array to import + * @param string|bool $index Index/name that the config variables are in + * @param array|bool $allowed List of allowed namespaces/directives + * @param bool $mq_fix Boolean whether or not to enable magic quotes fix + * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy + * + * @return mixed + */ + public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) + { + $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema); + $config = HTMLPurifier_Config::create($ret, $schema); + return $config; + } + + /** + * Merges in configuration values from $_GET/$_POST to object. NOT STATIC. + * + * @param array $array $_GET or $_POST array to import + * @param string|bool $index Index/name that the config variables are in + * @param array|bool $allowed List of allowed namespaces/directives + * @param bool $mq_fix Boolean whether or not to enable magic quotes fix + */ + public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) + { + $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def); + $this->loadArray($ret); + } + + /** + * Prepares an array from a form into something usable for the more + * strict parts of HTMLPurifier_Config + * + * @param array $array $_GET or $_POST array to import + * @param string|bool $index Index/name that the config variables are in + * @param array|bool $allowed List of allowed namespaces/directives + * @param bool $mq_fix Boolean whether or not to enable magic quotes fix + * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy + * + * @return array + */ + public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) + { + if ($index !== false) { + $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array(); + } + $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc(); + + $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema); + $ret = array(); + foreach ($allowed as $key) { + list($ns, $directive) = $key; + $skey = "$ns.$directive"; + if (!empty($array["Null_$skey"])) { + $ret[$ns][$directive] = null; + continue; + } + if (!isset($array[$skey])) { + continue; + } + $value = $mq ? stripslashes($array[$skey]) : $array[$skey]; + $ret[$ns][$directive] = $value; + } + return $ret; + } + + /** + * Loads configuration values from an ini file + * + * @param string $filename Name of ini file + */ + public function loadIni($filename) + { + if ($this->isFinalized('Cannot load directives after finalization')) { + return; + } + $array = parse_ini_file($filename, true); + $this->loadArray($array); + } + + /** + * Checks whether or not the configuration object is finalized. + * + * @param string|bool $error String error message, or false for no error + * + * @return bool + */ + public function isFinalized($error = false) + { + if ($this->finalized && $error) { + $this->triggerError($error, E_USER_ERROR); + } + return $this->finalized; + } + + /** + * Finalizes configuration only if auto finalize is on and not + * already finalized + */ + public function autoFinalize() + { + if ($this->autoFinalize) { + $this->finalize(); + } else { + $this->plist->squash(true); + } + } + + /** + * Finalizes a configuration object, prohibiting further change + */ + public function finalize() + { + $this->finalized = true; + $this->parser = null; + } + + /** + * Produces a nicely formatted error message by supplying the + * stack frame information OUTSIDE of HTMLPurifier_Config. + * + * @param string $msg An error message + * @param int $no An error number + */ + protected function triggerError($msg, $no) + { + // determine previous stack frame + $extra = ''; + if ($this->chatty) { + $trace = debug_backtrace(); + // zip(tail(trace), trace) -- but PHP is not Haskell har har + for ($i = 0, $c = count($trace); $i < $c - 1; $i++) { + // XXX this is not correct on some versions of HTML Purifier + if (isset($trace[$i + 1]['class']) && $trace[$i + 1]['class'] === 'HTMLPurifier_Config') { + continue; + } + $frame = $trace[$i]; + $extra = " invoked on line {$frame['line']} in file {$frame['file']}"; + break; + } + } + trigger_error($msg . $extra, $no); + } + + /** + * Returns a serialized form of the configuration object that can + * be reconstituted. + * + * @return string + */ + public function serialize() + { + $this->getDefinition('HTML'); + $this->getDefinition('CSS'); + $this->getDefinition('URI'); + return serialize($this); + } + +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema.php new file mode 100644 index 000000000..c3fe8cd4a --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema.php @@ -0,0 +1,176 @@ + array( + * 'Directive' => new stdClass(), + * ) + * ) + * + * The stdClass may have the following properties: + * + * - If isAlias isn't set: + * - type: Integer type of directive, see HTMLPurifier_VarParser for definitions + * - allow_null: If set, this directive allows null values + * - aliases: If set, an associative array of value aliases to real values + * - allowed: If set, a lookup array of allowed (string) values + * - If isAlias is set: + * - namespace: Namespace this directive aliases to + * - name: Directive name this directive aliases to + * + * In certain degenerate cases, stdClass will actually be an integer. In + * that case, the value is equivalent to an stdClass with the type + * property set to the integer. If the integer is negative, type is + * equal to the absolute value of integer, and allow_null is true. + * + * This class is friendly with HTMLPurifier_Config. If you need introspection + * about the schema, you're better of using the ConfigSchema_Interchange, + * which uses more memory but has much richer information. + * @type array + */ + public $info = array(); + + /** + * Application-wide singleton + * @type HTMLPurifier_ConfigSchema + */ + protected static $singleton; + + public function __construct() + { + $this->defaultPlist = new HTMLPurifier_PropertyList(); + } + + /** + * Unserializes the default ConfigSchema. + * @return HTMLPurifier_ConfigSchema + */ + public static function makeFromSerial() + { + $contents = file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema.ser'); + $r = unserialize($contents); + if (!$r) { + $hash = sha1($contents); + trigger_error("Unserialization of configuration schema failed, sha1 of file was $hash", E_USER_ERROR); + } + return $r; + } + + /** + * Retrieves an instance of the application-wide configuration definition. + * @param HTMLPurifier_ConfigSchema $prototype + * @return HTMLPurifier_ConfigSchema + */ + public static function instance($prototype = null) + { + if ($prototype !== null) { + HTMLPurifier_ConfigSchema::$singleton = $prototype; + } elseif (HTMLPurifier_ConfigSchema::$singleton === null || $prototype === true) { + HTMLPurifier_ConfigSchema::$singleton = HTMLPurifier_ConfigSchema::makeFromSerial(); + } + return HTMLPurifier_ConfigSchema::$singleton; + } + + /** + * Defines a directive for configuration + * @warning Will fail of directive's namespace is defined. + * @warning This method's signature is slightly different from the legacy + * define() static method! Beware! + * @param string $key Name of directive + * @param mixed $default Default value of directive + * @param string $type Allowed type of the directive. See + * HTMLPurifier_VarParser::$types for allowed values + * @param bool $allow_null Whether or not to allow null values + */ + public function add($key, $default, $type, $allow_null) + { + $obj = new stdClass(); + $obj->type = is_int($type) ? $type : HTMLPurifier_VarParser::$types[$type]; + if ($allow_null) { + $obj->allow_null = true; + } + $this->info[$key] = $obj; + $this->defaults[$key] = $default; + $this->defaultPlist->set($key, $default); + } + + /** + * Defines a directive value alias. + * + * Directive value aliases are convenient for developers because it lets + * them set a directive to several values and get the same result. + * @param string $key Name of Directive + * @param array $aliases Hash of aliased values to the real alias + */ + public function addValueAliases($key, $aliases) + { + if (!isset($this->info[$key]->aliases)) { + $this->info[$key]->aliases = array(); + } + foreach ($aliases as $alias => $real) { + $this->info[$key]->aliases[$alias] = $real; + } + } + + /** + * Defines a set of allowed values for a directive. + * @warning This is slightly different from the corresponding static + * method definition. + * @param string $key Name of directive + * @param array $allowed Lookup array of allowed values + */ + public function addAllowedValues($key, $allowed) + { + $this->info[$key]->allowed = $allowed; + } + + /** + * Defines a directive alias for backwards compatibility + * @param string $key Directive that will be aliased + * @param string $new_key Directive that the alias will be to + */ + public function addAlias($key, $new_key) + { + $obj = new stdClass; + $obj->key = $new_key; + $obj->isAlias = true; + $this->info[$key] = $obj; + } + + /** + * Replaces any stdClass that only has the type property with type integer. + */ + public function postProcess() + { + foreach ($this->info as $key => $v) { + if (count((array) $v) == 1) { + $this->info[$key] = $v->type; + } elseif (count((array) $v) == 2 && isset($v->allow_null)) { + $this->info[$key] = -$v->type; + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php similarity index 99% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php index 692aaa881..d5906cd46 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php @@ -46,4 +46,3 @@ class HTMLPurifier_ConfigSchema_Builder_ConfigSchema } // vim: et sw=4 sts=4 - diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/Xml.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Builder/Xml.php similarity index 99% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/Xml.php rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/Builder/Xml.php index 075916bfd..5fa56f7dd 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Builder/Xml.php +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Builder/Xml.php @@ -142,4 +142,3 @@ class HTMLPurifier_ConfigSchema_Builder_Xml extends XMLWriter } // vim: et sw=4 sts=4 - diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Builder/index.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Builder/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Builder/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Exception.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Exception.php similarity index 99% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Exception.php rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/Exception.php index 53e485eed..2671516c5 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Exception.php +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Exception.php @@ -9,4 +9,3 @@ class HTMLPurifier_ConfigSchema_Exception extends HTMLPurifier_Exception } // vim: et sw=4 sts=4 - diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange.php similarity index 99% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange.php rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange.php index 145762e5f..0e08ae8fe 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange.php +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange.php @@ -45,4 +45,3 @@ class HTMLPurifier_ConfigSchema_Interchange } // vim: et sw=4 sts=4 - diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Directive.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange/Directive.php similarity index 99% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Directive.php rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange/Directive.php index 03812709d..127a39a67 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Directive.php +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange/Directive.php @@ -87,4 +87,3 @@ class HTMLPurifier_ConfigSchema_Interchange_Directive } // vim: et sw=4 sts=4 - diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Id.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange/Id.php similarity index 99% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Id.php rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange/Id.php index 5ded05571..126f09d95 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Interchange/Id.php +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange/Id.php @@ -56,4 +56,3 @@ class HTMLPurifier_ConfigSchema_Interchange_Id } // vim: et sw=4 sts=4 - diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange/index.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Interchange/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/InterchangeBuilder.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/InterchangeBuilder.php similarity index 99% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/InterchangeBuilder.php rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/InterchangeBuilder.php index a8f35a7c5..655e6dd1b 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/InterchangeBuilder.php +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/InterchangeBuilder.php @@ -224,4 +224,3 @@ class HTMLPurifier_ConfigSchema_InterchangeBuilder } // vim: et sw=4 sts=4 - diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Validator.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Validator.php similarity index 99% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Validator.php rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/Validator.php index b9bf63057..fb3127788 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/Validator.php +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/Validator.php @@ -246,4 +246,3 @@ class HTMLPurifier_ConfigSchema_Validator } // vim: et sw=4 sts=4 - diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/ValidatorAtom.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/ValidatorAtom.php similarity index 99% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/ValidatorAtom.php rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/ValidatorAtom.php index 1a6f90e52..c9aa3644a 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/ValidatorAtom.php +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/ValidatorAtom.php @@ -128,4 +128,3 @@ class HTMLPurifier_ConfigSchema_ValidatorAtom } // vim: et sw=4 sts=4 - diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/index.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema.ser b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema.ser new file mode 100644 index 000000000..a5426c736 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema.ser @@ -0,0 +1 @@ +O:25:"HTMLPurifier_ConfigSchema":3:{s:8:"defaults";a:127:{s:19:"Attr.AllowedClasses";N;s:24:"Attr.AllowedFrameTargets";a:0:{}s:15:"Attr.AllowedRel";a:0:{}s:15:"Attr.AllowedRev";a:0:{}s:18:"Attr.ClassUseCDATA";N;s:20:"Attr.DefaultImageAlt";N;s:24:"Attr.DefaultInvalidImage";s:0:"";s:27:"Attr.DefaultInvalidImageAlt";s:13:"Invalid image";s:19:"Attr.DefaultTextDir";s:3:"ltr";s:13:"Attr.EnableID";b:0;s:21:"Attr.ForbiddenClasses";a:0:{}s:13:"Attr.ID.HTML5";N;s:16:"Attr.IDBlacklist";a:0:{}s:22:"Attr.IDBlacklistRegexp";N;s:13:"Attr.IDPrefix";s:0:"";s:18:"Attr.IDPrefixLocal";s:0:"";s:24:"AutoFormat.AutoParagraph";b:0;s:17:"AutoFormat.Custom";a:0:{}s:25:"AutoFormat.DisplayLinkURI";b:0;s:18:"AutoFormat.Linkify";b:0;s:33:"AutoFormat.PurifierLinkify.DocURL";s:3:"#%s";s:26:"AutoFormat.PurifierLinkify";b:0;s:32:"AutoFormat.RemoveEmpty.Predicate";a:4:{s:8:"colgroup";a:0:{}s:2:"th";a:0:{}s:2:"td";a:0:{}s:6:"iframe";a:1:{i:0;s:3:"src";}}s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";a:2:{s:2:"td";b:1;s:2:"th";b:1;}s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";b:0;s:22:"AutoFormat.RemoveEmpty";b:0;s:39:"AutoFormat.RemoveSpansWithoutAttributes";b:0;s:19:"CSS.AllowDuplicates";b:0;s:18:"CSS.AllowImportant";b:0;s:15:"CSS.AllowTricky";b:0;s:16:"CSS.AllowedFonts";N;s:21:"CSS.AllowedProperties";N;s:17:"CSS.DefinitionRev";i:1;s:23:"CSS.ForbiddenProperties";a:0:{}s:16:"CSS.MaxImgLength";s:6:"1200px";s:15:"CSS.Proprietary";b:0;s:11:"CSS.Trusted";b:0;s:20:"Cache.DefinitionImpl";s:10:"Serializer";s:20:"Cache.SerializerPath";N;s:27:"Cache.SerializerPermissions";i:493;s:22:"Core.AggressivelyFixLt";b:1;s:29:"Core.AggressivelyRemoveScript";b:1;s:28:"Core.AllowHostnameUnderscore";b:0;s:23:"Core.AllowParseManyTags";b:0;s:18:"Core.CollectErrors";b:0;s:18:"Core.ColorKeywords";a:148:{s:9:"aliceblue";s:7:"#F0F8FF";s:12:"antiquewhite";s:7:"#FAEBD7";s:4:"aqua";s:7:"#00FFFF";s:10:"aquamarine";s:7:"#7FFFD4";s:5:"azure";s:7:"#F0FFFF";s:5:"beige";s:7:"#F5F5DC";s:6:"bisque";s:7:"#FFE4C4";s:5:"black";s:7:"#000000";s:14:"blanchedalmond";s:7:"#FFEBCD";s:4:"blue";s:7:"#0000FF";s:10:"blueviolet";s:7:"#8A2BE2";s:5:"brown";s:7:"#A52A2A";s:9:"burlywood";s:7:"#DEB887";s:9:"cadetblue";s:7:"#5F9EA0";s:10:"chartreuse";s:7:"#7FFF00";s:9:"chocolate";s:7:"#D2691E";s:5:"coral";s:7:"#FF7F50";s:14:"cornflowerblue";s:7:"#6495ED";s:8:"cornsilk";s:7:"#FFF8DC";s:7:"crimson";s:7:"#DC143C";s:4:"cyan";s:7:"#00FFFF";s:8:"darkblue";s:7:"#00008B";s:8:"darkcyan";s:7:"#008B8B";s:13:"darkgoldenrod";s:7:"#B8860B";s:8:"darkgray";s:7:"#A9A9A9";s:8:"darkgrey";s:7:"#A9A9A9";s:9:"darkgreen";s:7:"#006400";s:9:"darkkhaki";s:7:"#BDB76B";s:11:"darkmagenta";s:7:"#8B008B";s:14:"darkolivegreen";s:7:"#556B2F";s:10:"darkorange";s:7:"#FF8C00";s:10:"darkorchid";s:7:"#9932CC";s:7:"darkred";s:7:"#8B0000";s:10:"darksalmon";s:7:"#E9967A";s:12:"darkseagreen";s:7:"#8FBC8F";s:13:"darkslateblue";s:7:"#483D8B";s:13:"darkslategray";s:7:"#2F4F4F";s:13:"darkslategrey";s:7:"#2F4F4F";s:13:"darkturquoise";s:7:"#00CED1";s:10:"darkviolet";s:7:"#9400D3";s:8:"deeppink";s:7:"#FF1493";s:11:"deepskyblue";s:7:"#00BFFF";s:7:"dimgray";s:7:"#696969";s:7:"dimgrey";s:7:"#696969";s:10:"dodgerblue";s:7:"#1E90FF";s:9:"firebrick";s:7:"#B22222";s:11:"floralwhite";s:7:"#FFFAF0";s:11:"forestgreen";s:7:"#228B22";s:7:"fuchsia";s:7:"#FF00FF";s:9:"gainsboro";s:7:"#DCDCDC";s:10:"ghostwhite";s:7:"#F8F8FF";s:4:"gold";s:7:"#FFD700";s:9:"goldenrod";s:7:"#DAA520";s:4:"gray";s:7:"#808080";s:4:"grey";s:7:"#808080";s:5:"green";s:7:"#008000";s:11:"greenyellow";s:7:"#ADFF2F";s:8:"honeydew";s:7:"#F0FFF0";s:7:"hotpink";s:7:"#FF69B4";s:9:"indianred";s:7:"#CD5C5C";s:6:"indigo";s:7:"#4B0082";s:5:"ivory";s:7:"#FFFFF0";s:5:"khaki";s:7:"#F0E68C";s:8:"lavender";s:7:"#E6E6FA";s:13:"lavenderblush";s:7:"#FFF0F5";s:9:"lawngreen";s:7:"#7CFC00";s:12:"lemonchiffon";s:7:"#FFFACD";s:9:"lightblue";s:7:"#ADD8E6";s:10:"lightcoral";s:7:"#F08080";s:9:"lightcyan";s:7:"#E0FFFF";s:20:"lightgoldenrodyellow";s:7:"#FAFAD2";s:9:"lightgray";s:7:"#D3D3D3";s:9:"lightgrey";s:7:"#D3D3D3";s:10:"lightgreen";s:7:"#90EE90";s:9:"lightpink";s:7:"#FFB6C1";s:11:"lightsalmon";s:7:"#FFA07A";s:13:"lightseagreen";s:7:"#20B2AA";s:12:"lightskyblue";s:7:"#87CEFA";s:14:"lightslategray";s:7:"#778899";s:14:"lightslategrey";s:7:"#778899";s:14:"lightsteelblue";s:7:"#B0C4DE";s:11:"lightyellow";s:7:"#FFFFE0";s:4:"lime";s:7:"#00FF00";s:9:"limegreen";s:7:"#32CD32";s:5:"linen";s:7:"#FAF0E6";s:7:"magenta";s:7:"#FF00FF";s:6:"maroon";s:7:"#800000";s:16:"mediumaquamarine";s:7:"#66CDAA";s:10:"mediumblue";s:7:"#0000CD";s:12:"mediumorchid";s:7:"#BA55D3";s:12:"mediumpurple";s:7:"#9370DB";s:14:"mediumseagreen";s:7:"#3CB371";s:15:"mediumslateblue";s:7:"#7B68EE";s:17:"mediumspringgreen";s:7:"#00FA9A";s:15:"mediumturquoise";s:7:"#48D1CC";s:15:"mediumvioletred";s:7:"#C71585";s:12:"midnightblue";s:7:"#191970";s:9:"mintcream";s:7:"#F5FFFA";s:9:"mistyrose";s:7:"#FFE4E1";s:8:"moccasin";s:7:"#FFE4B5";s:11:"navajowhite";s:7:"#FFDEAD";s:4:"navy";s:7:"#000080";s:7:"oldlace";s:7:"#FDF5E6";s:5:"olive";s:7:"#808000";s:9:"olivedrab";s:7:"#6B8E23";s:6:"orange";s:7:"#FFA500";s:9:"orangered";s:7:"#FF4500";s:6:"orchid";s:7:"#DA70D6";s:13:"palegoldenrod";s:7:"#EEE8AA";s:9:"palegreen";s:7:"#98FB98";s:13:"paleturquoise";s:7:"#AFEEEE";s:13:"palevioletred";s:7:"#DB7093";s:10:"papayawhip";s:7:"#FFEFD5";s:9:"peachpuff";s:7:"#FFDAB9";s:4:"peru";s:7:"#CD853F";s:4:"pink";s:7:"#FFC0CB";s:4:"plum";s:7:"#DDA0DD";s:10:"powderblue";s:7:"#B0E0E6";s:6:"purple";s:7:"#800080";s:13:"rebeccapurple";s:7:"#663399";s:3:"red";s:7:"#FF0000";s:9:"rosybrown";s:7:"#BC8F8F";s:9:"royalblue";s:7:"#4169E1";s:11:"saddlebrown";s:7:"#8B4513";s:6:"salmon";s:7:"#FA8072";s:10:"sandybrown";s:7:"#F4A460";s:8:"seagreen";s:7:"#2E8B57";s:8:"seashell";s:7:"#FFF5EE";s:6:"sienna";s:7:"#A0522D";s:6:"silver";s:7:"#C0C0C0";s:7:"skyblue";s:7:"#87CEEB";s:9:"slateblue";s:7:"#6A5ACD";s:9:"slategray";s:7:"#708090";s:9:"slategrey";s:7:"#708090";s:4:"snow";s:7:"#FFFAFA";s:11:"springgreen";s:7:"#00FF7F";s:9:"steelblue";s:7:"#4682B4";s:3:"tan";s:7:"#D2B48C";s:4:"teal";s:7:"#008080";s:7:"thistle";s:7:"#D8BFD8";s:6:"tomato";s:7:"#FF6347";s:9:"turquoise";s:7:"#40E0D0";s:6:"violet";s:7:"#EE82EE";s:5:"wheat";s:7:"#F5DEB3";s:5:"white";s:7:"#FFFFFF";s:10:"whitesmoke";s:7:"#F5F5F5";s:6:"yellow";s:7:"#FFFF00";s:11:"yellowgreen";s:7:"#9ACD32";}s:30:"Core.ConvertDocumentToFragment";b:1;s:36:"Core.DirectLexLineNumberSyncInterval";i:0;s:20:"Core.DisableExcludes";b:0;s:15:"Core.EnableIDNA";b:0;s:13:"Core.Encoding";s:5:"utf-8";s:26:"Core.EscapeInvalidChildren";b:0;s:22:"Core.EscapeInvalidTags";b:0;s:29:"Core.EscapeNonASCIICharacters";b:0;s:19:"Core.HiddenElements";a:2:{s:6:"script";b:1;s:5:"style";b:1;}s:13:"Core.Language";s:2:"en";s:24:"Core.LegacyEntityDecoder";b:0;s:14:"Core.LexerImpl";N;s:24:"Core.MaintainLineNumbers";N;s:22:"Core.NormalizeNewlines";b:1;s:21:"Core.RemoveInvalidImg";b:1;s:33:"Core.RemoveProcessingInstructions";b:0;s:25:"Core.RemoveScriptContents";N;s:13:"Filter.Custom";a:0:{}s:34:"Filter.ExtractStyleBlocks.Escaping";b:1;s:31:"Filter.ExtractStyleBlocks.Scope";N;s:34:"Filter.ExtractStyleBlocks.TidyImpl";N;s:25:"Filter.ExtractStyleBlocks";b:0;s:14:"Filter.YouTube";b:0;s:12:"HTML.Allowed";N;s:22:"HTML.AllowedAttributes";N;s:20:"HTML.AllowedComments";a:0:{}s:26:"HTML.AllowedCommentsRegexp";N;s:20:"HTML.AllowedElements";N;s:19:"HTML.AllowedModules";N;s:23:"HTML.Attr.Name.UseCDATA";b:0;s:17:"HTML.BlockWrapper";s:1:"p";s:16:"HTML.CoreModules";a:7:{s:9:"Structure";b:1;s:4:"Text";b:1;s:9:"Hypertext";b:1;s:4:"List";b:1;s:22:"NonXMLCommonAttributes";b:1;s:19:"XMLCommonAttributes";b:1;s:16:"CommonAttributes";b:1;}s:18:"HTML.CustomDoctype";N;s:17:"HTML.DefinitionID";N;s:18:"HTML.DefinitionRev";i:1;s:12:"HTML.Doctype";N;s:25:"HTML.FlashAllowFullScreen";b:0;s:24:"HTML.ForbiddenAttributes";a:0:{}s:22:"HTML.ForbiddenElements";a:0:{}s:10:"HTML.Forms";b:0;s:17:"HTML.MaxImgLength";i:1200;s:13:"HTML.Nofollow";b:0;s:11:"HTML.Parent";s:3:"div";s:16:"HTML.Proprietary";b:0;s:14:"HTML.SafeEmbed";b:0;s:15:"HTML.SafeIframe";b:0;s:15:"HTML.SafeObject";b:0;s:18:"HTML.SafeScripting";a:0:{}s:11:"HTML.Strict";b:0;s:16:"HTML.TargetBlank";b:0;s:19:"HTML.TargetNoopener";b:1;s:21:"HTML.TargetNoreferrer";b:1;s:12:"HTML.TidyAdd";a:0:{}s:14:"HTML.TidyLevel";s:6:"medium";s:15:"HTML.TidyRemove";a:0:{}s:12:"HTML.Trusted";b:0;s:10:"HTML.XHTML";b:1;s:28:"Output.CommentScriptContents";b:1;s:19:"Output.FixInnerHTML";b:1;s:18:"Output.FlashCompat";b:0;s:14:"Output.Newline";N;s:15:"Output.SortAttr";b:0;s:17:"Output.TidyFormat";b:0;s:17:"Test.ForceNoIconv";b:0;s:18:"URI.AllowedSchemes";a:7:{s:4:"http";b:1;s:5:"https";b:1;s:6:"mailto";b:1;s:3:"ftp";b:1;s:4:"nntp";b:1;s:4:"news";b:1;s:3:"tel";b:1;}s:8:"URI.Base";N;s:17:"URI.DefaultScheme";s:4:"http";s:16:"URI.DefinitionID";N;s:17:"URI.DefinitionRev";i:1;s:11:"URI.Disable";b:0;s:19:"URI.DisableExternal";b:0;s:28:"URI.DisableExternalResources";b:0;s:20:"URI.DisableResources";b:0;s:8:"URI.Host";N;s:17:"URI.HostBlacklist";a:0:{}s:16:"URI.MakeAbsolute";b:0;s:9:"URI.Munge";N;s:18:"URI.MungeResources";b:0;s:18:"URI.MungeSecretKey";N;s:26:"URI.OverrideAllowedSchemes";b:1;s:20:"URI.SafeIframeRegexp";N;}s:12:"defaultPlist";O:25:"HTMLPurifier_PropertyList":3:{s:7:"*data";a:127:{s:19:"Attr.AllowedClasses";N;s:24:"Attr.AllowedFrameTargets";a:0:{}s:15:"Attr.AllowedRel";a:0:{}s:15:"Attr.AllowedRev";a:0:{}s:18:"Attr.ClassUseCDATA";N;s:20:"Attr.DefaultImageAlt";N;s:24:"Attr.DefaultInvalidImage";s:0:"";s:27:"Attr.DefaultInvalidImageAlt";s:13:"Invalid image";s:19:"Attr.DefaultTextDir";s:3:"ltr";s:13:"Attr.EnableID";b:0;s:21:"Attr.ForbiddenClasses";a:0:{}s:13:"Attr.ID.HTML5";N;s:16:"Attr.IDBlacklist";a:0:{}s:22:"Attr.IDBlacklistRegexp";N;s:13:"Attr.IDPrefix";s:0:"";s:18:"Attr.IDPrefixLocal";s:0:"";s:24:"AutoFormat.AutoParagraph";b:0;s:17:"AutoFormat.Custom";a:0:{}s:25:"AutoFormat.DisplayLinkURI";b:0;s:18:"AutoFormat.Linkify";b:0;s:33:"AutoFormat.PurifierLinkify.DocURL";s:3:"#%s";s:26:"AutoFormat.PurifierLinkify";b:0;s:32:"AutoFormat.RemoveEmpty.Predicate";a:4:{s:8:"colgroup";a:0:{}s:2:"th";a:0:{}s:2:"td";a:0:{}s:6:"iframe";a:1:{i:0;s:3:"src";}}s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";a:2:{s:2:"td";b:1;s:2:"th";b:1;}s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";b:0;s:22:"AutoFormat.RemoveEmpty";b:0;s:39:"AutoFormat.RemoveSpansWithoutAttributes";b:0;s:19:"CSS.AllowDuplicates";b:0;s:18:"CSS.AllowImportant";b:0;s:15:"CSS.AllowTricky";b:0;s:16:"CSS.AllowedFonts";N;s:21:"CSS.AllowedProperties";N;s:17:"CSS.DefinitionRev";i:1;s:23:"CSS.ForbiddenProperties";a:0:{}s:16:"CSS.MaxImgLength";s:6:"1200px";s:15:"CSS.Proprietary";b:0;s:11:"CSS.Trusted";b:0;s:20:"Cache.DefinitionImpl";s:10:"Serializer";s:20:"Cache.SerializerPath";N;s:27:"Cache.SerializerPermissions";i:493;s:22:"Core.AggressivelyFixLt";b:1;s:29:"Core.AggressivelyRemoveScript";b:1;s:28:"Core.AllowHostnameUnderscore";b:0;s:23:"Core.AllowParseManyTags";b:0;s:18:"Core.CollectErrors";b:0;s:18:"Core.ColorKeywords";a:148:{s:9:"aliceblue";s:7:"#F0F8FF";s:12:"antiquewhite";s:7:"#FAEBD7";s:4:"aqua";s:7:"#00FFFF";s:10:"aquamarine";s:7:"#7FFFD4";s:5:"azure";s:7:"#F0FFFF";s:5:"beige";s:7:"#F5F5DC";s:6:"bisque";s:7:"#FFE4C4";s:5:"black";s:7:"#000000";s:14:"blanchedalmond";s:7:"#FFEBCD";s:4:"blue";s:7:"#0000FF";s:10:"blueviolet";s:7:"#8A2BE2";s:5:"brown";s:7:"#A52A2A";s:9:"burlywood";s:7:"#DEB887";s:9:"cadetblue";s:7:"#5F9EA0";s:10:"chartreuse";s:7:"#7FFF00";s:9:"chocolate";s:7:"#D2691E";s:5:"coral";s:7:"#FF7F50";s:14:"cornflowerblue";s:7:"#6495ED";s:8:"cornsilk";s:7:"#FFF8DC";s:7:"crimson";s:7:"#DC143C";s:4:"cyan";s:7:"#00FFFF";s:8:"darkblue";s:7:"#00008B";s:8:"darkcyan";s:7:"#008B8B";s:13:"darkgoldenrod";s:7:"#B8860B";s:8:"darkgray";s:7:"#A9A9A9";s:8:"darkgrey";s:7:"#A9A9A9";s:9:"darkgreen";s:7:"#006400";s:9:"darkkhaki";s:7:"#BDB76B";s:11:"darkmagenta";s:7:"#8B008B";s:14:"darkolivegreen";s:7:"#556B2F";s:10:"darkorange";s:7:"#FF8C00";s:10:"darkorchid";s:7:"#9932CC";s:7:"darkred";s:7:"#8B0000";s:10:"darksalmon";s:7:"#E9967A";s:12:"darkseagreen";s:7:"#8FBC8F";s:13:"darkslateblue";s:7:"#483D8B";s:13:"darkslategray";s:7:"#2F4F4F";s:13:"darkslategrey";s:7:"#2F4F4F";s:13:"darkturquoise";s:7:"#00CED1";s:10:"darkviolet";s:7:"#9400D3";s:8:"deeppink";s:7:"#FF1493";s:11:"deepskyblue";s:7:"#00BFFF";s:7:"dimgray";s:7:"#696969";s:7:"dimgrey";s:7:"#696969";s:10:"dodgerblue";s:7:"#1E90FF";s:9:"firebrick";s:7:"#B22222";s:11:"floralwhite";s:7:"#FFFAF0";s:11:"forestgreen";s:7:"#228B22";s:7:"fuchsia";s:7:"#FF00FF";s:9:"gainsboro";s:7:"#DCDCDC";s:10:"ghostwhite";s:7:"#F8F8FF";s:4:"gold";s:7:"#FFD700";s:9:"goldenrod";s:7:"#DAA520";s:4:"gray";s:7:"#808080";s:4:"grey";s:7:"#808080";s:5:"green";s:7:"#008000";s:11:"greenyellow";s:7:"#ADFF2F";s:8:"honeydew";s:7:"#F0FFF0";s:7:"hotpink";s:7:"#FF69B4";s:9:"indianred";s:7:"#CD5C5C";s:6:"indigo";s:7:"#4B0082";s:5:"ivory";s:7:"#FFFFF0";s:5:"khaki";s:7:"#F0E68C";s:8:"lavender";s:7:"#E6E6FA";s:13:"lavenderblush";s:7:"#FFF0F5";s:9:"lawngreen";s:7:"#7CFC00";s:12:"lemonchiffon";s:7:"#FFFACD";s:9:"lightblue";s:7:"#ADD8E6";s:10:"lightcoral";s:7:"#F08080";s:9:"lightcyan";s:7:"#E0FFFF";s:20:"lightgoldenrodyellow";s:7:"#FAFAD2";s:9:"lightgray";s:7:"#D3D3D3";s:9:"lightgrey";s:7:"#D3D3D3";s:10:"lightgreen";s:7:"#90EE90";s:9:"lightpink";s:7:"#FFB6C1";s:11:"lightsalmon";s:7:"#FFA07A";s:13:"lightseagreen";s:7:"#20B2AA";s:12:"lightskyblue";s:7:"#87CEFA";s:14:"lightslategray";s:7:"#778899";s:14:"lightslategrey";s:7:"#778899";s:14:"lightsteelblue";s:7:"#B0C4DE";s:11:"lightyellow";s:7:"#FFFFE0";s:4:"lime";s:7:"#00FF00";s:9:"limegreen";s:7:"#32CD32";s:5:"linen";s:7:"#FAF0E6";s:7:"magenta";s:7:"#FF00FF";s:6:"maroon";s:7:"#800000";s:16:"mediumaquamarine";s:7:"#66CDAA";s:10:"mediumblue";s:7:"#0000CD";s:12:"mediumorchid";s:7:"#BA55D3";s:12:"mediumpurple";s:7:"#9370DB";s:14:"mediumseagreen";s:7:"#3CB371";s:15:"mediumslateblue";s:7:"#7B68EE";s:17:"mediumspringgreen";s:7:"#00FA9A";s:15:"mediumturquoise";s:7:"#48D1CC";s:15:"mediumvioletred";s:7:"#C71585";s:12:"midnightblue";s:7:"#191970";s:9:"mintcream";s:7:"#F5FFFA";s:9:"mistyrose";s:7:"#FFE4E1";s:8:"moccasin";s:7:"#FFE4B5";s:11:"navajowhite";s:7:"#FFDEAD";s:4:"navy";s:7:"#000080";s:7:"oldlace";s:7:"#FDF5E6";s:5:"olive";s:7:"#808000";s:9:"olivedrab";s:7:"#6B8E23";s:6:"orange";s:7:"#FFA500";s:9:"orangered";s:7:"#FF4500";s:6:"orchid";s:7:"#DA70D6";s:13:"palegoldenrod";s:7:"#EEE8AA";s:9:"palegreen";s:7:"#98FB98";s:13:"paleturquoise";s:7:"#AFEEEE";s:13:"palevioletred";s:7:"#DB7093";s:10:"papayawhip";s:7:"#FFEFD5";s:9:"peachpuff";s:7:"#FFDAB9";s:4:"peru";s:7:"#CD853F";s:4:"pink";s:7:"#FFC0CB";s:4:"plum";s:7:"#DDA0DD";s:10:"powderblue";s:7:"#B0E0E6";s:6:"purple";s:7:"#800080";s:13:"rebeccapurple";s:7:"#663399";s:3:"red";s:7:"#FF0000";s:9:"rosybrown";s:7:"#BC8F8F";s:9:"royalblue";s:7:"#4169E1";s:11:"saddlebrown";s:7:"#8B4513";s:6:"salmon";s:7:"#FA8072";s:10:"sandybrown";s:7:"#F4A460";s:8:"seagreen";s:7:"#2E8B57";s:8:"seashell";s:7:"#FFF5EE";s:6:"sienna";s:7:"#A0522D";s:6:"silver";s:7:"#C0C0C0";s:7:"skyblue";s:7:"#87CEEB";s:9:"slateblue";s:7:"#6A5ACD";s:9:"slategray";s:7:"#708090";s:9:"slategrey";s:7:"#708090";s:4:"snow";s:7:"#FFFAFA";s:11:"springgreen";s:7:"#00FF7F";s:9:"steelblue";s:7:"#4682B4";s:3:"tan";s:7:"#D2B48C";s:4:"teal";s:7:"#008080";s:7:"thistle";s:7:"#D8BFD8";s:6:"tomato";s:7:"#FF6347";s:9:"turquoise";s:7:"#40E0D0";s:6:"violet";s:7:"#EE82EE";s:5:"wheat";s:7:"#F5DEB3";s:5:"white";s:7:"#FFFFFF";s:10:"whitesmoke";s:7:"#F5F5F5";s:6:"yellow";s:7:"#FFFF00";s:11:"yellowgreen";s:7:"#9ACD32";}s:30:"Core.ConvertDocumentToFragment";b:1;s:36:"Core.DirectLexLineNumberSyncInterval";i:0;s:20:"Core.DisableExcludes";b:0;s:15:"Core.EnableIDNA";b:0;s:13:"Core.Encoding";s:5:"utf-8";s:26:"Core.EscapeInvalidChildren";b:0;s:22:"Core.EscapeInvalidTags";b:0;s:29:"Core.EscapeNonASCIICharacters";b:0;s:19:"Core.HiddenElements";a:2:{s:6:"script";b:1;s:5:"style";b:1;}s:13:"Core.Language";s:2:"en";s:24:"Core.LegacyEntityDecoder";b:0;s:14:"Core.LexerImpl";N;s:24:"Core.MaintainLineNumbers";N;s:22:"Core.NormalizeNewlines";b:1;s:21:"Core.RemoveInvalidImg";b:1;s:33:"Core.RemoveProcessingInstructions";b:0;s:25:"Core.RemoveScriptContents";N;s:13:"Filter.Custom";a:0:{}s:34:"Filter.ExtractStyleBlocks.Escaping";b:1;s:31:"Filter.ExtractStyleBlocks.Scope";N;s:34:"Filter.ExtractStyleBlocks.TidyImpl";N;s:25:"Filter.ExtractStyleBlocks";b:0;s:14:"Filter.YouTube";b:0;s:12:"HTML.Allowed";N;s:22:"HTML.AllowedAttributes";N;s:20:"HTML.AllowedComments";a:0:{}s:26:"HTML.AllowedCommentsRegexp";N;s:20:"HTML.AllowedElements";N;s:19:"HTML.AllowedModules";N;s:23:"HTML.Attr.Name.UseCDATA";b:0;s:17:"HTML.BlockWrapper";s:1:"p";s:16:"HTML.CoreModules";a:7:{s:9:"Structure";b:1;s:4:"Text";b:1;s:9:"Hypertext";b:1;s:4:"List";b:1;s:22:"NonXMLCommonAttributes";b:1;s:19:"XMLCommonAttributes";b:1;s:16:"CommonAttributes";b:1;}s:18:"HTML.CustomDoctype";N;s:17:"HTML.DefinitionID";N;s:18:"HTML.DefinitionRev";i:1;s:12:"HTML.Doctype";N;s:25:"HTML.FlashAllowFullScreen";b:0;s:24:"HTML.ForbiddenAttributes";a:0:{}s:22:"HTML.ForbiddenElements";a:0:{}s:10:"HTML.Forms";b:0;s:17:"HTML.MaxImgLength";i:1200;s:13:"HTML.Nofollow";b:0;s:11:"HTML.Parent";s:3:"div";s:16:"HTML.Proprietary";b:0;s:14:"HTML.SafeEmbed";b:0;s:15:"HTML.SafeIframe";b:0;s:15:"HTML.SafeObject";b:0;s:18:"HTML.SafeScripting";a:0:{}s:11:"HTML.Strict";b:0;s:16:"HTML.TargetBlank";b:0;s:19:"HTML.TargetNoopener";b:1;s:21:"HTML.TargetNoreferrer";b:1;s:12:"HTML.TidyAdd";a:0:{}s:14:"HTML.TidyLevel";s:6:"medium";s:15:"HTML.TidyRemove";a:0:{}s:12:"HTML.Trusted";b:0;s:10:"HTML.XHTML";b:1;s:28:"Output.CommentScriptContents";b:1;s:19:"Output.FixInnerHTML";b:1;s:18:"Output.FlashCompat";b:0;s:14:"Output.Newline";N;s:15:"Output.SortAttr";b:0;s:17:"Output.TidyFormat";b:0;s:17:"Test.ForceNoIconv";b:0;s:18:"URI.AllowedSchemes";a:7:{s:4:"http";b:1;s:5:"https";b:1;s:6:"mailto";b:1;s:3:"ftp";b:1;s:4:"nntp";b:1;s:4:"news";b:1;s:3:"tel";b:1;}s:8:"URI.Base";N;s:17:"URI.DefaultScheme";s:4:"http";s:16:"URI.DefinitionID";N;s:17:"URI.DefinitionRev";i:1;s:11:"URI.Disable";b:0;s:19:"URI.DisableExternal";b:0;s:28:"URI.DisableExternalResources";b:0;s:20:"URI.DisableResources";b:0;s:8:"URI.Host";N;s:17:"URI.HostBlacklist";a:0:{}s:16:"URI.MakeAbsolute";b:0;s:9:"URI.Munge";N;s:18:"URI.MungeResources";b:0;s:18:"URI.MungeSecretKey";N;s:26:"URI.OverrideAllowedSchemes";b:1;s:20:"URI.SafeIframeRegexp";N;}s:9:"*parent";N;s:8:"*cache";N;}s:4:"info";a:140:{s:19:"Attr.AllowedClasses";i:-8;s:24:"Attr.AllowedFrameTargets";i:8;s:15:"Attr.AllowedRel";i:8;s:15:"Attr.AllowedRev";i:8;s:18:"Attr.ClassUseCDATA";i:-7;s:20:"Attr.DefaultImageAlt";i:-1;s:24:"Attr.DefaultInvalidImage";i:1;s:27:"Attr.DefaultInvalidImageAlt";i:1;s:19:"Attr.DefaultTextDir";O:8:"stdClass":2:{s:4:"type";i:1;s:7:"allowed";a:2:{s:3:"ltr";b:1;s:3:"rtl";b:1;}}s:13:"Attr.EnableID";i:7;s:17:"HTML.EnableAttrID";O:8:"stdClass":2:{s:3:"key";s:13:"Attr.EnableID";s:7:"isAlias";b:1;}s:21:"Attr.ForbiddenClasses";i:8;s:13:"Attr.ID.HTML5";i:-7;s:16:"Attr.IDBlacklist";i:9;s:22:"Attr.IDBlacklistRegexp";i:-1;s:13:"Attr.IDPrefix";i:1;s:18:"Attr.IDPrefixLocal";i:1;s:24:"AutoFormat.AutoParagraph";i:7;s:17:"AutoFormat.Custom";i:9;s:25:"AutoFormat.DisplayLinkURI";i:7;s:18:"AutoFormat.Linkify";i:7;s:33:"AutoFormat.PurifierLinkify.DocURL";i:1;s:37:"AutoFormatParam.PurifierLinkifyDocURL";O:8:"stdClass":2:{s:3:"key";s:33:"AutoFormat.PurifierLinkify.DocURL";s:7:"isAlias";b:1;}s:26:"AutoFormat.PurifierLinkify";i:7;s:32:"AutoFormat.RemoveEmpty.Predicate";i:10;s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";i:8;s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";i:7;s:22:"AutoFormat.RemoveEmpty";i:7;s:39:"AutoFormat.RemoveSpansWithoutAttributes";i:7;s:19:"CSS.AllowDuplicates";i:7;s:18:"CSS.AllowImportant";i:7;s:15:"CSS.AllowTricky";i:7;s:16:"CSS.AllowedFonts";i:-8;s:21:"CSS.AllowedProperties";i:-8;s:17:"CSS.DefinitionRev";i:5;s:23:"CSS.ForbiddenProperties";i:8;s:16:"CSS.MaxImgLength";i:-1;s:15:"CSS.Proprietary";i:7;s:11:"CSS.Trusted";i:7;s:20:"Cache.DefinitionImpl";i:-1;s:20:"Core.DefinitionCache";O:8:"stdClass":2:{s:3:"key";s:20:"Cache.DefinitionImpl";s:7:"isAlias";b:1;}s:20:"Cache.SerializerPath";i:-1;s:27:"Cache.SerializerPermissions";i:-5;s:22:"Core.AggressivelyFixLt";i:7;s:29:"Core.AggressivelyRemoveScript";i:7;s:28:"Core.AllowHostnameUnderscore";i:7;s:23:"Core.AllowParseManyTags";i:7;s:18:"Core.CollectErrors";i:7;s:18:"Core.ColorKeywords";i:10;s:30:"Core.ConvertDocumentToFragment";i:7;s:24:"Core.AcceptFullDocuments";O:8:"stdClass":2:{s:3:"key";s:30:"Core.ConvertDocumentToFragment";s:7:"isAlias";b:1;}s:36:"Core.DirectLexLineNumberSyncInterval";i:5;s:20:"Core.DisableExcludes";i:7;s:15:"Core.EnableIDNA";i:7;s:13:"Core.Encoding";i:2;s:26:"Core.EscapeInvalidChildren";i:7;s:22:"Core.EscapeInvalidTags";i:7;s:29:"Core.EscapeNonASCIICharacters";i:7;s:19:"Core.HiddenElements";i:8;s:13:"Core.Language";i:1;s:24:"Core.LegacyEntityDecoder";i:7;s:14:"Core.LexerImpl";i:-11;s:24:"Core.MaintainLineNumbers";i:-7;s:22:"Core.NormalizeNewlines";i:7;s:21:"Core.RemoveInvalidImg";i:7;s:33:"Core.RemoveProcessingInstructions";i:7;s:25:"Core.RemoveScriptContents";i:-7;s:13:"Filter.Custom";i:9;s:34:"Filter.ExtractStyleBlocks.Escaping";i:7;s:33:"Filter.ExtractStyleBlocksEscaping";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.Escaping";s:7:"isAlias";b:1;}s:38:"FilterParam.ExtractStyleBlocksEscaping";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.Escaping";s:7:"isAlias";b:1;}s:31:"Filter.ExtractStyleBlocks.Scope";i:-1;s:30:"Filter.ExtractStyleBlocksScope";O:8:"stdClass":2:{s:3:"key";s:31:"Filter.ExtractStyleBlocks.Scope";s:7:"isAlias";b:1;}s:35:"FilterParam.ExtractStyleBlocksScope";O:8:"stdClass":2:{s:3:"key";s:31:"Filter.ExtractStyleBlocks.Scope";s:7:"isAlias";b:1;}s:34:"Filter.ExtractStyleBlocks.TidyImpl";i:-11;s:38:"FilterParam.ExtractStyleBlocksTidyImpl";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.TidyImpl";s:7:"isAlias";b:1;}s:25:"Filter.ExtractStyleBlocks";i:7;s:14:"Filter.YouTube";i:7;s:12:"HTML.Allowed";i:-4;s:22:"HTML.AllowedAttributes";i:-8;s:20:"HTML.AllowedComments";i:8;s:26:"HTML.AllowedCommentsRegexp";i:-1;s:20:"HTML.AllowedElements";i:-8;s:19:"HTML.AllowedModules";i:-8;s:23:"HTML.Attr.Name.UseCDATA";i:7;s:17:"HTML.BlockWrapper";i:1;s:16:"HTML.CoreModules";i:8;s:18:"HTML.CustomDoctype";i:-1;s:17:"HTML.DefinitionID";i:-1;s:18:"HTML.DefinitionRev";i:5;s:12:"HTML.Doctype";O:8:"stdClass":3:{s:4:"type";i:1;s:10:"allow_null";b:1;s:7:"allowed";a:5:{s:22:"HTML 4.01 Transitional";b:1;s:16:"HTML 4.01 Strict";b:1;s:22:"XHTML 1.0 Transitional";b:1;s:16:"XHTML 1.0 Strict";b:1;s:9:"XHTML 1.1";b:1;}}s:25:"HTML.FlashAllowFullScreen";i:7;s:24:"HTML.ForbiddenAttributes";i:8;s:22:"HTML.ForbiddenElements";i:8;s:10:"HTML.Forms";i:7;s:17:"HTML.MaxImgLength";i:-5;s:13:"HTML.Nofollow";i:7;s:11:"HTML.Parent";i:1;s:16:"HTML.Proprietary";i:7;s:14:"HTML.SafeEmbed";i:7;s:15:"HTML.SafeIframe";i:7;s:15:"HTML.SafeObject";i:7;s:18:"HTML.SafeScripting";i:8;s:11:"HTML.Strict";i:7;s:16:"HTML.TargetBlank";i:7;s:19:"HTML.TargetNoopener";i:7;s:21:"HTML.TargetNoreferrer";i:7;s:12:"HTML.TidyAdd";i:8;s:14:"HTML.TidyLevel";O:8:"stdClass":2:{s:4:"type";i:1;s:7:"allowed";a:4:{s:4:"none";b:1;s:5:"light";b:1;s:6:"medium";b:1;s:5:"heavy";b:1;}}s:15:"HTML.TidyRemove";i:8;s:12:"HTML.Trusted";i:7;s:10:"HTML.XHTML";i:7;s:10:"Core.XHTML";O:8:"stdClass":2:{s:3:"key";s:10:"HTML.XHTML";s:7:"isAlias";b:1;}s:28:"Output.CommentScriptContents";i:7;s:26:"Core.CommentScriptContents";O:8:"stdClass":2:{s:3:"key";s:28:"Output.CommentScriptContents";s:7:"isAlias";b:1;}s:19:"Output.FixInnerHTML";i:7;s:18:"Output.FlashCompat";i:7;s:14:"Output.Newline";i:-1;s:15:"Output.SortAttr";i:7;s:17:"Output.TidyFormat";i:7;s:15:"Core.TidyFormat";O:8:"stdClass":2:{s:3:"key";s:17:"Output.TidyFormat";s:7:"isAlias";b:1;}s:17:"Test.ForceNoIconv";i:7;s:18:"URI.AllowedSchemes";i:8;s:8:"URI.Base";i:-1;s:17:"URI.DefaultScheme";i:-1;s:16:"URI.DefinitionID";i:-1;s:17:"URI.DefinitionRev";i:5;s:11:"URI.Disable";i:7;s:15:"Attr.DisableURI";O:8:"stdClass":2:{s:3:"key";s:11:"URI.Disable";s:7:"isAlias";b:1;}s:19:"URI.DisableExternal";i:7;s:28:"URI.DisableExternalResources";i:7;s:20:"URI.DisableResources";i:7;s:8:"URI.Host";i:-1;s:17:"URI.HostBlacklist";i:9;s:16:"URI.MakeAbsolute";i:7;s:9:"URI.Munge";i:-1;s:18:"URI.MungeResources";i:7;s:18:"URI.MungeSecretKey";i:-1;s:26:"URI.OverrideAllowedSchemes";i:7;s:20:"URI.SafeIframeRegexp";i:-1;}} \ No newline at end of file diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt new file mode 100644 index 000000000..735d4b7a1 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt @@ -0,0 +1,10 @@ +Attr.ID.HTML5 +TYPE: bool/null +DEFAULT: null +VERSION: 4.8.0 +--DESCRIPTION-- +In HTML5, restrictions on the format of the id attribute have been significantly +relaxed, such that any string is valid so long as it contains no spaces and +is at least one character. In lieu of a general HTML5 compatibility flag, +set this configuration directive to true to use the relaxed rules. +--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt new file mode 100644 index 000000000..6367fe23c --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt @@ -0,0 +1,14 @@ +AutoFormat.RemoveEmpty.Predicate +TYPE: hash +VERSION: 4.7.0 +DEFAULT: array('colgroup' => array(), 'th' => array(), 'td' => array(), 'iframe' => array('src')) +--DESCRIPTION-- +

+ Given that an element has no contents, it will be removed by default, unless + this predicate dictates otherwise. The predicate can either be an associative + map from tag name to list of attributes that must be present for the element + to be considered preserved: thus, the default always preserves colgroup, + th and td, and also iframe if it + has a src. +

+--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt similarity index 89% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt index ca17eb1dc..9228dee22 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt @@ -6,7 +6,7 @@ DEFAULT: false

When enabled, HTML Purifier will treat any elements that contain only non-breaking spaces as well as regular whitespace as empty, and remove - them when %AutoForamt.RemoveEmpty is enabled. + them when %AutoFormat.RemoveEmpty is enabled.

See %AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions for a list of elements diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt new file mode 100644 index 000000000..4d054b1f0 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt @@ -0,0 +1,11 @@ +CSS.AllowDuplicates +TYPE: bool +DEFAULT: false +VERSION: 4.8.0 +--DESCRIPTION-- +

+ By default, HTML Purifier removes duplicate CSS properties, + like color:red; color:blue. If this is set to + true, duplicate properties are allowed. +

+--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt similarity index 59% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt index b2b83d9ab..2e0cc8104 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt @@ -1,5 +1,5 @@ Cache.SerializerPermissions -TYPE: int +TYPE: int/null VERSION: 4.3.0 DEFAULT: 0755 --DESCRIPTION-- @@ -8,4 +8,9 @@ DEFAULT: 0755 Directory permissions of the files and directories created inside the DefinitionCache/Serializer or other custom serializer path.

+

+ In HTML Purifier 4.8.0, this also supports NULL, + which means that no chmod'ing or directory creation shall + occur. +

--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt new file mode 100644 index 000000000..b2b6ab149 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt @@ -0,0 +1,16 @@ +Core.AggressivelyRemoveScript +TYPE: bool +VERSION: 4.9.0 +DEFAULT: true +--DESCRIPTION-- +

+ This directive enables aggressive pre-filter removal of + script tags. This is not necessary for security, + but it can help work around a bug in libxml where embedded + HTML elements inside script sections cause the parser to + choke. To revert to pre-4.9.0 behavior, set this to false. + This directive has no effect if %Core.Trusted is true, + %Core.RemoveScriptContents is false, or %Core.HiddenElements + does not contain script. +

+--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt new file mode 100644 index 000000000..06278f82a --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt @@ -0,0 +1,12 @@ +Core.AllowParseManyTags +TYPE: bool +DEFAULT: false +VERSION: 4.10.1 +--DESCRIPTION-- +

+ This directive allows parsing of many nested tags. + If you set true, relaxes any hardcoded limit from the parser. + However, in that case it may cause a Dos attack. + Be careful when enabling it. +

+--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt new file mode 100644 index 000000000..a75844cd5 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt @@ -0,0 +1,160 @@ +Core.ColorKeywords +TYPE: hash +VERSION: 2.0.0 +--DEFAULT-- +array ( + 'aliceblue' => '#F0F8FF', + 'antiquewhite' => '#FAEBD7', + 'aqua' => '#00FFFF', + 'aquamarine' => '#7FFFD4', + 'azure' => '#F0FFFF', + 'beige' => '#F5F5DC', + 'bisque' => '#FFE4C4', + 'black' => '#000000', + 'blanchedalmond' => '#FFEBCD', + 'blue' => '#0000FF', + 'blueviolet' => '#8A2BE2', + 'brown' => '#A52A2A', + 'burlywood' => '#DEB887', + 'cadetblue' => '#5F9EA0', + 'chartreuse' => '#7FFF00', + 'chocolate' => '#D2691E', + 'coral' => '#FF7F50', + 'cornflowerblue' => '#6495ED', + 'cornsilk' => '#FFF8DC', + 'crimson' => '#DC143C', + 'cyan' => '#00FFFF', + 'darkblue' => '#00008B', + 'darkcyan' => '#008B8B', + 'darkgoldenrod' => '#B8860B', + 'darkgray' => '#A9A9A9', + 'darkgrey' => '#A9A9A9', + 'darkgreen' => '#006400', + 'darkkhaki' => '#BDB76B', + 'darkmagenta' => '#8B008B', + 'darkolivegreen' => '#556B2F', + 'darkorange' => '#FF8C00', + 'darkorchid' => '#9932CC', + 'darkred' => '#8B0000', + 'darksalmon' => '#E9967A', + 'darkseagreen' => '#8FBC8F', + 'darkslateblue' => '#483D8B', + 'darkslategray' => '#2F4F4F', + 'darkslategrey' => '#2F4F4F', + 'darkturquoise' => '#00CED1', + 'darkviolet' => '#9400D3', + 'deeppink' => '#FF1493', + 'deepskyblue' => '#00BFFF', + 'dimgray' => '#696969', + 'dimgrey' => '#696969', + 'dodgerblue' => '#1E90FF', + 'firebrick' => '#B22222', + 'floralwhite' => '#FFFAF0', + 'forestgreen' => '#228B22', + 'fuchsia' => '#FF00FF', + 'gainsboro' => '#DCDCDC', + 'ghostwhite' => '#F8F8FF', + 'gold' => '#FFD700', + 'goldenrod' => '#DAA520', + 'gray' => '#808080', + 'grey' => '#808080', + 'green' => '#008000', + 'greenyellow' => '#ADFF2F', + 'honeydew' => '#F0FFF0', + 'hotpink' => '#FF69B4', + 'indianred' => '#CD5C5C', + 'indigo' => '#4B0082', + 'ivory' => '#FFFFF0', + 'khaki' => '#F0E68C', + 'lavender' => '#E6E6FA', + 'lavenderblush' => '#FFF0F5', + 'lawngreen' => '#7CFC00', + 'lemonchiffon' => '#FFFACD', + 'lightblue' => '#ADD8E6', + 'lightcoral' => '#F08080', + 'lightcyan' => '#E0FFFF', + 'lightgoldenrodyellow' => '#FAFAD2', + 'lightgray' => '#D3D3D3', + 'lightgrey' => '#D3D3D3', + 'lightgreen' => '#90EE90', + 'lightpink' => '#FFB6C1', + 'lightsalmon' => '#FFA07A', + 'lightseagreen' => '#20B2AA', + 'lightskyblue' => '#87CEFA', + 'lightslategray' => '#778899', + 'lightslategrey' => '#778899', + 'lightsteelblue' => '#B0C4DE', + 'lightyellow' => '#FFFFE0', + 'lime' => '#00FF00', + 'limegreen' => '#32CD32', + 'linen' => '#FAF0E6', + 'magenta' => '#FF00FF', + 'maroon' => '#800000', + 'mediumaquamarine' => '#66CDAA', + 'mediumblue' => '#0000CD', + 'mediumorchid' => '#BA55D3', + 'mediumpurple' => '#9370DB', + 'mediumseagreen' => '#3CB371', + 'mediumslateblue' => '#7B68EE', + 'mediumspringgreen' => '#00FA9A', + 'mediumturquoise' => '#48D1CC', + 'mediumvioletred' => '#C71585', + 'midnightblue' => '#191970', + 'mintcream' => '#F5FFFA', + 'mistyrose' => '#FFE4E1', + 'moccasin' => '#FFE4B5', + 'navajowhite' => '#FFDEAD', + 'navy' => '#000080', + 'oldlace' => '#FDF5E6', + 'olive' => '#808000', + 'olivedrab' => '#6B8E23', + 'orange' => '#FFA500', + 'orangered' => '#FF4500', + 'orchid' => '#DA70D6', + 'palegoldenrod' => '#EEE8AA', + 'palegreen' => '#98FB98', + 'paleturquoise' => '#AFEEEE', + 'palevioletred' => '#DB7093', + 'papayawhip' => '#FFEFD5', + 'peachpuff' => '#FFDAB9', + 'peru' => '#CD853F', + 'pink' => '#FFC0CB', + 'plum' => '#DDA0DD', + 'powderblue' => '#B0E0E6', + 'purple' => '#800080', + 'rebeccapurple' => '#663399', + 'red' => '#FF0000', + 'rosybrown' => '#BC8F8F', + 'royalblue' => '#4169E1', + 'saddlebrown' => '#8B4513', + 'salmon' => '#FA8072', + 'sandybrown' => '#F4A460', + 'seagreen' => '#2E8B57', + 'seashell' => '#FFF5EE', + 'sienna' => '#A0522D', + 'silver' => '#C0C0C0', + 'skyblue' => '#87CEEB', + 'slateblue' => '#6A5ACD', + 'slategray' => '#708090', + 'slategrey' => '#708090', + 'snow' => '#FFFAFA', + 'springgreen' => '#00FF7F', + 'steelblue' => '#4682B4', + 'tan' => '#D2B48C', + 'teal' => '#008080', + 'thistle' => '#D8BFD8', + 'tomato' => '#FF6347', + 'turquoise' => '#40E0D0', + 'violet' => '#EE82EE', + 'wheat' => '#F5DEB3', + 'white' => '#FFFFFF', + 'whitesmoke' => '#F5F5F5', + 'yellow' => '#FFFF00', + 'yellowgreen' => '#9ACD32' +) +--DESCRIPTION-- + +Lookup array of color names to six digit hexadecimal number corresponding +to color, with preceding hash mark. Used when parsing colors. The lookup +is done in a case-insensitive manner. +--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.Language.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.Language.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.Language.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.Language.txt diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt new file mode 100644 index 000000000..392b43649 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt @@ -0,0 +1,36 @@ +Core.LegacyEntityDecoder +TYPE: bool +VERSION: 4.9.0 +DEFAULT: false +--DESCRIPTION-- +

+ Prior to HTML Purifier 4.9.0, entities were decoded by performing + a global search replace for all entities whose decoded versions + did not have special meanings under HTML, and replaced them with + their decoded versions. We would match all entities, even if they did + not have a trailing semicolon, but only if there weren't any trailing + alphanumeric characters. +

+
'.$this->l('Bank name').''.$information['recipient_banking_instruction']['bank_name'].'

- {$rm_v['data_form']|date_format:"%d-%m-%Y"} + {$rm_v['data_form']}

- {$rm_v['data_to']|date_format:"%d-%m-%Y"} + {$rm_v['data_to']}

diff --git a/themes/hotel-reservation-theme/header.tpl b/themes/hotel-reservation-theme/header.tpl index 06414cb87..bc6fc2e1c 100644 --- a/themes/hotel-reservation-theme/header.tpl +++ b/themes/hotel-reservation-theme/header.tpl @@ -75,7 +75,7 @@ - + {if !isset($content_only) || !$content_only} {if isset($restricted_country_mode) && $restricted_country_mode}
diff --git a/tools/htmlpurifier/HTMLPurifier.auto.php b/tools/htmlpurifier/HTMLPurifier.auto.php new file mode 100644 index 000000000..1960c399f --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier.auto.php @@ -0,0 +1,11 @@ +purify($html, $config); +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier.includes.php b/tools/htmlpurifier/HTMLPurifier.includes.php new file mode 100644 index 000000000..151e6752d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier.includes.php @@ -0,0 +1,234 @@ + $attributes) { + $allowed_elements[$element] = true; + foreach ($attributes as $attribute => $x) { + $allowed_attributes["$element.$attribute"] = true; + } + } + $config->set('HTML.AllowedElements', $allowed_elements); + $config->set('HTML.AllowedAttributes', $allowed_attributes); + if ($allowed_protocols !== null) { + $config->set('URI.AllowedSchemes', $allowed_protocols); + } + $purifier = new HTMLPurifier($config); + return $purifier->purify($string); +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier.path.php b/tools/htmlpurifier/HTMLPurifier.path.php new file mode 100644 index 000000000..39b1b6531 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier.path.php @@ -0,0 +1,11 @@ +config = HTMLPurifier_Config::create($config); + $this->strategy = new HTMLPurifier_Strategy_Core(); + } + + /** + * Adds a filter to process the output. First come first serve + * + * @param HTMLPurifier_Filter $filter HTMLPurifier_Filter object + */ + public function addFilter($filter) + { + trigger_error( + 'HTMLPurifier->addFilter() is deprecated, use configuration directives' . + ' in the Filter namespace or Filter.Custom', + E_USER_WARNING + ); + $this->filters[] = $filter; + } + + /** + * Filters an HTML snippet/document to be XSS-free and standards-compliant. + * + * @param string $html String of HTML to purify + * @param HTMLPurifier_Config $config Config object for this operation, + * if omitted, defaults to the config object specified during this + * object's construction. The parameter can also be any type + * that HTMLPurifier_Config::create() supports. + * + * @return string Purified HTML + */ + public function purify($html, $config = null) + { + // :TODO: make the config merge in, instead of replace + $config = $config ? HTMLPurifier_Config::create($config) : $this->config; + + // implementation is partially environment dependant, partially + // configuration dependant + $lexer = HTMLPurifier_Lexer::create($config); + + $context = new HTMLPurifier_Context(); + + // setup HTML generator + $this->generator = new HTMLPurifier_Generator($config, $context); + $context->register('Generator', $this->generator); + + // set up global context variables + if ($config->get('Core.CollectErrors')) { + // may get moved out if other facilities use it + $language_factory = HTMLPurifier_LanguageFactory::instance(); + $language = $language_factory->create($config, $context); + $context->register('Locale', $language); + + $error_collector = new HTMLPurifier_ErrorCollector($context); + $context->register('ErrorCollector', $error_collector); + } + + // setup id_accumulator context, necessary due to the fact that + // AttrValidator can be called from many places + $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context); + $context->register('IDAccumulator', $id_accumulator); + + $html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context); + + // setup filters + $filter_flags = $config->getBatch('Filter'); + $custom_filters = $filter_flags['Custom']; + unset($filter_flags['Custom']); + $filters = array(); + foreach ($filter_flags as $filter => $flag) { + if (!$flag) { + continue; + } + if (strpos($filter, '.') !== false) { + continue; + } + $class = "HTMLPurifier_Filter_$filter"; + $filters[] = new $class; + } + foreach ($custom_filters as $filter) { + // maybe "HTMLPurifier_Filter_$filter", but be consistent with AutoFormat + $filters[] = $filter; + } + $filters = array_merge($filters, $this->filters); + // maybe prepare(), but later + + for ($i = 0, $filter_size = count($filters); $i < $filter_size; $i++) { + $html = $filters[$i]->preFilter($html, $config, $context); + } + + // purified HTML + $html = + $this->generator->generateFromTokens( + // list of tokens + $this->strategy->execute( + // list of un-purified tokens + $lexer->tokenizeHTML( + // un-purified HTML + $html, + $config, + $context + ), + $config, + $context + ) + ); + + for ($i = $filter_size - 1; $i >= 0; $i--) { + $html = $filters[$i]->postFilter($html, $config, $context); + } + + $html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context); + $this->context =& $context; + return $html; + } + + /** + * Filters an array of HTML snippets + * + * @param string[] $array_of_html Array of html snippets + * @param HTMLPurifier_Config $config Optional config object for this operation. + * See HTMLPurifier::purify() for more details. + * + * @return string[] Array of purified HTML + */ + public function purifyArray($array_of_html, $config = null) + { + $context_array = array(); + $array = array(); + foreach($array_of_html as $key=>$value){ + if (is_array($value)) { + $array[$key] = $this->purifyArray($value, $config); + } else { + $array[$key] = $this->purify($value, $config); + } + $context_array[$key] = $this->context; + } + $this->context = $context_array; + return $array; + } + + /** + * Singleton for enforcing just one HTML Purifier in your system + * + * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype + * HTMLPurifier instance to overload singleton with, + * or HTMLPurifier_Config instance to configure the + * generated version with. + * + * @return HTMLPurifier + */ + public static function instance($prototype = null) + { + if (!self::$instance || $prototype) { + if ($prototype instanceof HTMLPurifier) { + self::$instance = $prototype; + } elseif ($prototype) { + self::$instance = new HTMLPurifier($prototype); + } else { + self::$instance = new HTMLPurifier(); + } + } + return self::$instance; + } + + /** + * Singleton for enforcing just one HTML Purifier in your system + * + * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype + * HTMLPurifier instance to overload singleton with, + * or HTMLPurifier_Config instance to configure the + * generated version with. + * + * @return HTMLPurifier + * @note Backwards compatibility, see instance() + */ + public static function getInstance($prototype = null) + { + return HTMLPurifier::instance($prototype); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier.safe-includes.php b/tools/htmlpurifier/HTMLPurifier.safe-includes.php new file mode 100644 index 000000000..a3261f8a3 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier.safe-includes.php @@ -0,0 +1,228 @@ +config = HTMLPurifier_Config::create($config); - $this->strategy = new HTMLPurifier_Strategy_Core(); - } - - /** - * Adds a filter to process the output. First come first serve - * - * @param HTMLPurifier_Filter $filter HTMLPurifier_Filter object - */ - public function addFilter($filter) - { - trigger_error( - 'HTMLPurifier->addFilter() is deprecated, use configuration directives' . - ' in the Filter namespace or Filter.Custom', - E_USER_WARNING - ); - $this->filters[] = $filter; - } - - /** - * Filters an HTML snippet/document to be XSS-free and standards-compliant. - * - * @param string $html String of HTML to purify - * @param HTMLPurifier_Config $config Config object for this operation, - * if omitted, defaults to the config object specified during this - * object's construction. The parameter can also be any type - * that HTMLPurifier_Config::create() supports. - * - * @return string Purified HTML - */ - public function purify($html, $config = null) - { - // :TODO: make the config merge in, instead of replace - $config = $config ? HTMLPurifier_Config::create($config) : $this->config; - - // implementation is partially environment dependant, partially - // configuration dependant - $lexer = HTMLPurifier_Lexer::create($config); - - $context = new HTMLPurifier_Context(); - - // setup HTML generator - $this->generator = new HTMLPurifier_Generator($config, $context); - $context->register('Generator', $this->generator); - - // set up global context variables - if ($config->get('Core.CollectErrors')) { - // may get moved out if other facilities use it - $language_factory = HTMLPurifier_LanguageFactory::instance(); - $language = $language_factory->create($config, $context); - $context->register('Locale', $language); - - $error_collector = new HTMLPurifier_ErrorCollector($context); - $context->register('ErrorCollector', $error_collector); - } - - // setup id_accumulator context, necessary due to the fact that - // AttrValidator can be called from many places - $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context); - $context->register('IDAccumulator', $id_accumulator); - - $html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context); - - // setup filters - $filter_flags = $config->getBatch('Filter'); - $custom_filters = $filter_flags['Custom']; - unset($filter_flags['Custom']); - $filters = array(); - foreach ($filter_flags as $filter => $flag) { - if (!$flag) { - continue; - } - if (strpos($filter, '.') !== false) { - continue; - } - $class = "HTMLPurifier_Filter_$filter"; - $filters[] = new $class; - } - foreach ($custom_filters as $filter) { - // maybe "HTMLPurifier_Filter_$filter", but be consistent with AutoFormat - $filters[] = $filter; - } - $filters = array_merge($filters, $this->filters); - // maybe prepare(), but later - - for ($i = 0, $filter_size = count($filters); $i < $filter_size; $i++) { - $html = $filters[$i]->preFilter($html, $config, $context); - } - - // purified HTML - $html = - $this->generator->generateFromTokens( - // list of tokens - $this->strategy->execute( - // list of un-purified tokens - $lexer->tokenizeHTML( - // un-purified HTML - $html, - $config, - $context - ), - $config, - $context - ) - ); - - for ($i = $filter_size - 1; $i >= 0; $i--) { - $html = $filters[$i]->postFilter($html, $config, $context); - } - - $html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context); - $this->context =& $context; - return $html; - } - - /** - * Filters an array of HTML snippets - * - * @param string[] $array_of_html Array of html snippets - * @param HTMLPurifier_Config $config Optional config object for this operation. - * See HTMLPurifier::purify() for more details. - * - * @return string[] Array of purified HTML - */ - public function purifyArray($array_of_html, $config = null) - { - $context_array = array(); - foreach ($array_of_html as $key => $html) { - $array_of_html[$key] = $this->purify($html, $config); - $context_array[$key] = $this->context; - } - $this->context = $context_array; - return $array_of_html; - } - - /** - * Singleton for enforcing just one HTML Purifier in your system - * - * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype - * HTMLPurifier instance to overload singleton with, - * or HTMLPurifier_Config instance to configure the - * generated version with. - * - * @return HTMLPurifier - */ - public static function instance($prototype = null) - { - if (!self::$instance || $prototype) { - if ($prototype instanceof HTMLPurifier) { - self::$instance = $prototype; - } elseif ($prototype) { - self::$instance = new HTMLPurifier($prototype); - } else { - self::$instance = new HTMLPurifier(); - } - } - return self::$instance; - } - - /** - * Singleton for enforcing just one HTML Purifier in your system - * - * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype - * HTMLPurifier instance to overload singleton with, - * or HTMLPurifier_Config instance to configure the - * generated version with. - * - * @return HTMLPurifier - * @note Backwards compatibility, see instance() - */ - public static function getInstance($prototype = null) - { - return HTMLPurifier::instance($prototype); - } -} - - - - - -/** - * Converts a stream of HTMLPurifier_Token into an HTMLPurifier_Node, - * and back again. - * - * @note This transformation is not an equivalence. We mutate the input - * token stream to make it so; see all [MUT] markers in code. - */ -class HTMLPurifier_Arborize -{ - public static function arborize($tokens, $config, $context) { - $definition = $config->getHTMLDefinition(); - $parent = new HTMLPurifier_Token_Start($definition->info_parent); - $stack = array($parent->toNode()); - foreach ($tokens as $token) { - $token->skip = null; // [MUT] - $token->carryover = null; // [MUT] - if ($token instanceof HTMLPurifier_Token_End) { - $token->start = null; // [MUT] - $r = array_pop($stack); - assert($r->name === $token->name); - assert(empty($token->attr)); - $r->endCol = $token->col; - $r->endLine = $token->line; - $r->endArmor = $token->armor; - continue; - } - $node = $token->toNode(); - $stack[count($stack)-1]->children[] = $node; - if ($token instanceof HTMLPurifier_Token_Start) { - $stack[] = $node; - } - } - assert(count($stack) == 1); - return $stack[0]; - } - - public static function flatten($node, $config, $context) { - $level = 0; - $nodes = array($level => new HTMLPurifier_Queue(array($node))); - $closingTokens = array(); - $tokens = array(); - do { - while (!$nodes[$level]->isEmpty()) { - $node = $nodes[$level]->shift(); // FIFO - list($start, $end) = $node->toTokenPair(); - if ($level > 0) { - $tokens[] = $start; - } - if ($end !== null) { - $closingTokens[$level][] = $end; - } - if ($node instanceof HTMLPurifier_Node_Element) { - $level++; - $nodes[$level] = new HTMLPurifier_Queue(); - foreach ($node->children as $childNode) { - $nodes[$level]->push($childNode); - } - } - } - $level--; - if ($level && isset($closingTokens[$level])) { - while ($token = array_pop($closingTokens[$level])) { - $tokens[] = $token; - } - } - } while ($level > 0); - return $tokens; - } -} - - - -/** - * Defines common attribute collections that modules reference - */ - -class HTMLPurifier_AttrCollections -{ - - /** - * Associative array of attribute collections, indexed by name. - * @type array - */ - public $info = array(); - - /** - * Performs all expansions on internal data for use by other inclusions - * It also collects all attribute collection extensions from - * modules - * @param HTMLPurifier_AttrTypes $attr_types HTMLPurifier_AttrTypes instance - * @param HTMLPurifier_HTMLModule[] $modules Hash array of HTMLPurifier_HTMLModule members - */ - public function __construct($attr_types, $modules) - { - // load extensions from the modules - foreach ($modules as $module) { - foreach ($module->attr_collections as $coll_i => $coll) { - if (!isset($this->info[$coll_i])) { - $this->info[$coll_i] = array(); - } - foreach ($coll as $attr_i => $attr) { - if ($attr_i === 0 && isset($this->info[$coll_i][$attr_i])) { - // merge in includes - $this->info[$coll_i][$attr_i] = array_merge( - $this->info[$coll_i][$attr_i], - $attr - ); - continue; - } - $this->info[$coll_i][$attr_i] = $attr; - } - } - } - // perform internal expansions and inclusions - foreach ($this->info as $name => $attr) { - // merge attribute collections that include others - $this->performInclusions($this->info[$name]); - // replace string identifiers with actual attribute objects - $this->expandIdentifiers($this->info[$name], $attr_types); - } - } - - /** - * Takes a reference to an attribute associative array and performs - * all inclusions specified by the zero index. - * @param array &$attr Reference to attribute array - */ - public function performInclusions(&$attr) - { - if (!isset($attr[0])) { - return; - } - $merge = $attr[0]; - $seen = array(); // recursion guard - // loop through all the inclusions - for ($i = 0; isset($merge[$i]); $i++) { - if (isset($seen[$merge[$i]])) { - continue; - } - $seen[$merge[$i]] = true; - // foreach attribute of the inclusion, copy it over - if (!isset($this->info[$merge[$i]])) { - continue; - } - foreach ($this->info[$merge[$i]] as $key => $value) { - if (isset($attr[$key])) { - continue; - } // also catches more inclusions - $attr[$key] = $value; - } - if (isset($this->info[$merge[$i]][0])) { - // recursion - $merge = array_merge($merge, $this->info[$merge[$i]][0]); - } - } - unset($attr[0]); - } - - /** - * Expands all string identifiers in an attribute array by replacing - * them with the appropriate values inside HTMLPurifier_AttrTypes - * @param array &$attr Reference to attribute array - * @param HTMLPurifier_AttrTypes $attr_types HTMLPurifier_AttrTypes instance - */ - public function expandIdentifiers(&$attr, $attr_types) - { - // because foreach will process new elements we add, make sure we - // skip duplicates - $processed = array(); - - foreach ($attr as $def_i => $def) { - // skip inclusions - if ($def_i === 0) { - continue; - } - - if (isset($processed[$def_i])) { - continue; - } - - // determine whether or not attribute is required - if ($required = (strpos($def_i, '*') !== false)) { - // rename the definition - unset($attr[$def_i]); - $def_i = trim($def_i, '*'); - $attr[$def_i] = $def; - } - - $processed[$def_i] = true; - - // if we've already got a literal object, move on - if (is_object($def)) { - // preserve previous required - $attr[$def_i]->required = ($required || $attr[$def_i]->required); - continue; - } - - if ($def === false) { - unset($attr[$def_i]); - continue; - } - - if ($t = $attr_types->get($def)) { - $attr[$def_i] = $t; - $attr[$def_i]->required = $required; - } else { - unset($attr[$def_i]); - } - } - } -} - - - - - -/** - * Base class for all validating attribute definitions. - * - * This family of classes forms the core for not only HTML attribute validation, - * but also any sort of string that needs to be validated or cleaned (which - * means CSS properties and composite definitions are defined here too). - * Besides defining (through code) what precisely makes the string valid, - * subclasses are also responsible for cleaning the code if possible. - */ - -abstract class HTMLPurifier_AttrDef -{ - - /** - * Tells us whether or not an HTML attribute is minimized. - * Has no meaning in other contexts. - * @type bool - */ - public $minimized = false; - - /** - * Tells us whether or not an HTML attribute is required. - * Has no meaning in other contexts - * @type bool - */ - public $required = false; - - /** - * Validates and cleans passed string according to a definition. - * - * @param string $string String to be validated and cleaned. - * @param HTMLPurifier_Config $config Mandatory HTMLPurifier_Config object. - * @param HTMLPurifier_Context $context Mandatory HTMLPurifier_Context object. - */ - abstract public function validate($string, $config, $context); - - /** - * Convenience method that parses a string as if it were CDATA. - * - * This method process a string in the manner specified at - * by removing - * leading and trailing whitespace, ignoring line feeds, and replacing - * carriage returns and tabs with spaces. While most useful for HTML - * attributes specified as CDATA, it can also be applied to most CSS - * values. - * - * @note This method is not entirely standards compliant, as trim() removes - * more types of whitespace than specified in the spec. In practice, - * this is rarely a problem, as those extra characters usually have - * already been removed by HTMLPurifier_Encoder. - * - * @warning This processing is inconsistent with XML's whitespace handling - * as specified by section 3.3.3 and referenced XHTML 1.0 section - * 4.7. However, note that we are NOT necessarily - * parsing XML, thus, this behavior may still be correct. We - * assume that newlines have been normalized. - */ - public function parseCDATA($string) - { - $string = trim($string); - $string = str_replace(array("\n", "\t", "\r"), ' ', $string); - return $string; - } - - /** - * Factory method for creating this class from a string. - * @param string $string String construction info - * @return HTMLPurifier_AttrDef Created AttrDef object corresponding to $string - */ - public function make($string) - { - // default implementation, return a flyweight of this object. - // If $string has an effect on the returned object (i.e. you - // need to overload this method), it is best - // to clone or instantiate new copies. (Instantiation is safer.) - return $this; - } - - /** - * Removes spaces from rgb(0, 0, 0) so that shorthand CSS properties work - * properly. THIS IS A HACK! - * @param string $string a CSS colour definition - * @return string - */ - protected function mungeRgb($string) - { - return preg_replace('/rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)/', 'rgb(\1,\2,\3)', $string); - } - - /** - * Parses a possibly escaped CSS string and returns the "pure" - * version of it. - */ - protected function expandCSSEscape($string) - { - // flexibly parse it - $ret = ''; - for ($i = 0, $c = strlen($string); $i < $c; $i++) { - if ($string[$i] === '\\') { - $i++; - if ($i >= $c) { - $ret .= '\\'; - break; - } - if (ctype_xdigit($string[$i])) { - $code = $string[$i]; - for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) { - if (!ctype_xdigit($string[$i])) { - break; - } - $code .= $string[$i]; - } - // We have to be extremely careful when adding - // new characters, to make sure we're not breaking - // the encoding. - $char = HTMLPurifier_Encoder::unichr(hexdec($code)); - if (HTMLPurifier_Encoder::cleanUTF8($char) === '') { - continue; - } - $ret .= $char; - if ($i < $c && trim($string[$i]) !== '') { - $i--; - } - continue; - } - if ($string[$i] === "\n") { - continue; - } - } - $ret .= $string[$i]; - } - return $ret; - } -} - - - - - -/** - * Processes an entire attribute array for corrections needing multiple values. - * - * Occasionally, a certain attribute will need to be removed and popped onto - * another value. Instead of creating a complex return syntax for - * HTMLPurifier_AttrDef, we just pass the whole attribute array to a - * specialized object and have that do the special work. That is the - * family of HTMLPurifier_AttrTransform. - * - * An attribute transformation can be assigned to run before or after - * HTMLPurifier_AttrDef validation. See HTMLPurifier_HTMLDefinition for - * more details. - */ - -abstract class HTMLPurifier_AttrTransform -{ - - /** - * Abstract: makes changes to the attributes dependent on multiple values. - * - * @param array $attr Assoc array of attributes, usually from - * HTMLPurifier_Token_Tag::$attr - * @param HTMLPurifier_Config $config Mandatory HTMLPurifier_Config object. - * @param HTMLPurifier_Context $context Mandatory HTMLPurifier_Context object - * @return array Processed attribute array. - */ - abstract public function transform($attr, $config, $context); - - /** - * Prepends CSS properties to the style attribute, creating the - * attribute if it doesn't exist. - * @param array &$attr Attribute array to process (passed by reference) - * @param string $css CSS to prepend - */ - public function prependCSS(&$attr, $css) - { - $attr['style'] = isset($attr['style']) ? $attr['style'] : ''; - $attr['style'] = $css . $attr['style']; - } - - /** - * Retrieves and removes an attribute - * @param array &$attr Attribute array to process (passed by reference) - * @param mixed $key Key of attribute to confiscate - * @return mixed - */ - public function confiscateAttr(&$attr, $key) - { - if (!isset($attr[$key])) { - return null; - } - $value = $attr[$key]; - unset($attr[$key]); - return $value; - } -} - - - - - -/** - * Provides lookup array of attribute types to HTMLPurifier_AttrDef objects - */ -class HTMLPurifier_AttrTypes -{ - /** - * Lookup array of attribute string identifiers to concrete implementations. - * @type HTMLPurifier_AttrDef[] - */ - protected $info = array(); - - /** - * Constructs the info array, supplying default implementations for attribute - * types. - */ - public function __construct() - { - // XXX This is kind of poor, since we don't actually /clone/ - // instances; instead, we use the supplied make() attribute. So, - // the underlying class must know how to deal with arguments. - // With the old implementation of Enum, that ignored its - // arguments when handling a make dispatch, the IAlign - // definition wouldn't work. - - // pseudo-types, must be instantiated via shorthand - $this->info['Enum'] = new HTMLPurifier_AttrDef_Enum(); - $this->info['Bool'] = new HTMLPurifier_AttrDef_HTML_Bool(); - - $this->info['CDATA'] = new HTMLPurifier_AttrDef_Text(); - $this->info['ID'] = new HTMLPurifier_AttrDef_HTML_ID(); - $this->info['Length'] = new HTMLPurifier_AttrDef_HTML_Length(); - $this->info['MultiLength'] = new HTMLPurifier_AttrDef_HTML_MultiLength(); - $this->info['NMTOKENS'] = new HTMLPurifier_AttrDef_HTML_Nmtokens(); - $this->info['Pixels'] = new HTMLPurifier_AttrDef_HTML_Pixels(); - $this->info['Text'] = new HTMLPurifier_AttrDef_Text(); - $this->info['URI'] = new HTMLPurifier_AttrDef_URI(); - $this->info['LanguageCode'] = new HTMLPurifier_AttrDef_Lang(); - $this->info['Color'] = new HTMLPurifier_AttrDef_HTML_Color(); - $this->info['IAlign'] = self::makeEnum('top,middle,bottom,left,right'); - $this->info['LAlign'] = self::makeEnum('top,bottom,left,right'); - $this->info['FrameTarget'] = new HTMLPurifier_AttrDef_HTML_FrameTarget(); - - // unimplemented aliases - $this->info['ContentType'] = new HTMLPurifier_AttrDef_Text(); - $this->info['ContentTypes'] = new HTMLPurifier_AttrDef_Text(); - $this->info['Charsets'] = new HTMLPurifier_AttrDef_Text(); - $this->info['Character'] = new HTMLPurifier_AttrDef_Text(); - - // "proprietary" types - $this->info['Class'] = new HTMLPurifier_AttrDef_HTML_Class(); - - // number is really a positive integer (one or more digits) - // FIXME: ^^ not always, see start and value of list items - $this->info['Number'] = new HTMLPurifier_AttrDef_Integer(false, false, true); - } - - private static function makeEnum($in) - { - return new HTMLPurifier_AttrDef_Clone(new HTMLPurifier_AttrDef_Enum(explode(',', $in))); - } - - /** - * Retrieves a type - * @param string $type String type name - * @return HTMLPurifier_AttrDef Object AttrDef for type - */ - public function get($type) - { - // determine if there is any extra info tacked on - if (strpos($type, '#') !== false) { - list($type, $string) = explode('#', $type, 2); - } else { - $string = ''; - } - - if (!isset($this->info[$type])) { - trigger_error('Cannot retrieve undefined attribute type ' . $type, E_USER_ERROR); - return; - } - return $this->info[$type]->make($string); - } - - /** - * Sets a new implementation for a type - * @param string $type String type name - * @param HTMLPurifier_AttrDef $impl Object AttrDef for type - */ - public function set($type, $impl) - { - $this->info[$type] = $impl; - } -} - - - - - -/** - * Validates the attributes of a token. Doesn't manage required attributes - * very well. The only reason we factored this out was because RemoveForeignElements - * also needed it besides ValidateAttributes. - */ -class HTMLPurifier_AttrValidator -{ - - /** - * Validates the attributes of a token, mutating it as necessary. - * that has valid tokens - * @param HTMLPurifier_Token $token Token to validate. - * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config - * @param HTMLPurifier_Context $context Instance of HTMLPurifier_Context - */ - public function validateToken($token, $config, $context) - { - $definition = $config->getHTMLDefinition(); - $e =& $context->get('ErrorCollector', true); - - // initialize IDAccumulator if necessary - $ok =& $context->get('IDAccumulator', true); - if (!$ok) { - $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context); - $context->register('IDAccumulator', $id_accumulator); - } - - // initialize CurrentToken if necessary - $current_token =& $context->get('CurrentToken', true); - if (!$current_token) { - $context->register('CurrentToken', $token); - } - - if (!$token instanceof HTMLPurifier_Token_Start && - !$token instanceof HTMLPurifier_Token_Empty - ) { - return; - } - - // create alias to global definition array, see also $defs - // DEFINITION CALL - $d_defs = $definition->info_global_attr; - - // don't update token until the very end, to ensure an atomic update - $attr = $token->attr; - - // do global transformations (pre) - // nothing currently utilizes this - foreach ($definition->info_attr_transform_pre as $transform) { - $attr = $transform->transform($o = $attr, $config, $context); - if ($e) { - if ($attr != $o) { - $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); - } - } - } - - // do local transformations only applicable to this element (pre) - // ex.

to

- foreach ($definition->info[$token->name]->attr_transform_pre as $transform) { - $attr = $transform->transform($o = $attr, $config, $context); - if ($e) { - if ($attr != $o) { - $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); - } - } - } - - // create alias to this element's attribute definition array, see - // also $d_defs (global attribute definition array) - // DEFINITION CALL - $defs = $definition->info[$token->name]->attr; - - $attr_key = false; - $context->register('CurrentAttr', $attr_key); - - // iterate through all the attribute keypairs - // Watch out for name collisions: $key has previously been used - foreach ($attr as $attr_key => $value) { - - // call the definition - if (isset($defs[$attr_key])) { - // there is a local definition defined - if ($defs[$attr_key] === false) { - // We've explicitly been told not to allow this element. - // This is usually when there's a global definition - // that must be overridden. - // Theoretically speaking, we could have a - // AttrDef_DenyAll, but this is faster! - $result = false; - } else { - // validate according to the element's definition - $result = $defs[$attr_key]->validate( - $value, - $config, - $context - ); - } - } elseif (isset($d_defs[$attr_key])) { - // there is a global definition defined, validate according - // to the global definition - $result = $d_defs[$attr_key]->validate( - $value, - $config, - $context - ); - } else { - // system never heard of the attribute? DELETE! - $result = false; - } - - // put the results into effect - if ($result === false || $result === null) { - // this is a generic error message that should replaced - // with more specific ones when possible - if ($e) { - $e->send(E_ERROR, 'AttrValidator: Attribute removed'); - } - - // remove the attribute - unset($attr[$attr_key]); - } elseif (is_string($result)) { - // generally, if a substitution is happening, there - // was some sort of implicit correction going on. We'll - // delegate it to the attribute classes to say exactly what. - - // simple substitution - $attr[$attr_key] = $result; - } else { - // nothing happens - } - - // we'd also want slightly more complicated substitution - // involving an array as the return value, - // although we're not sure how colliding attributes would - // resolve (certain ones would be completely overriden, - // others would prepend themselves). - } - - $context->destroy('CurrentAttr'); - - // post transforms - - // global (error reporting untested) - foreach ($definition->info_attr_transform_post as $transform) { - $attr = $transform->transform($o = $attr, $config, $context); - if ($e) { - if ($attr != $o) { - $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); - } - } - } - - // local (error reporting untested) - foreach ($definition->info[$token->name]->attr_transform_post as $transform) { - $attr = $transform->transform($o = $attr, $config, $context); - if ($e) { - if ($attr != $o) { - $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); - } - } - } - - $token->attr = $attr; - - // destroy CurrentToken if we made it ourselves - if (!$current_token) { - $context->destroy('CurrentToken'); - } - - } - - -} - - - - - -// constants are slow, so we use as few as possible -if (!defined('HTMLPURIFIER_PREFIX')) { - define('HTMLPURIFIER_PREFIX', dirname(__FILE__) . '/standalone'); - set_include_path(HTMLPURIFIER_PREFIX . PATH_SEPARATOR . get_include_path()); -} - -// accomodations for versions earlier than 5.0.2 -// borrowed from PHP_Compat, LGPL licensed, by Aidan Lister -if (!defined('PHP_EOL')) { - switch (strtoupper(substr(PHP_OS, 0, 3))) { - case 'WIN': - define('PHP_EOL', "\r\n"); - break; - case 'DAR': - define('PHP_EOL', "\r"); - break; - default: - define('PHP_EOL', "\n"); - } -} - -/** - * Bootstrap class that contains meta-functionality for HTML Purifier such as - * the autoload function. - * - * @note - * This class may be used without any other files from HTML Purifier. - */ -class HTMLPurifier_Bootstrap -{ - - /** - * Autoload function for HTML Purifier - * @param string $class Class to load - * @return bool - */ - public static function autoload($class) - { - $file = HTMLPurifier_Bootstrap::getPath($class); - if (!$file) { - return false; - } - // Technically speaking, it should be ok and more efficient to - // just do 'require', but Antonio Parraga reports that with - // Zend extensions such as Zend debugger and APC, this invariant - // may be broken. Since we have efficient alternatives, pay - // the cost here and avoid the bug. - require_once HTMLPURIFIER_PREFIX . '/' . $file; - return true; - } - - /** - * Returns the path for a specific class. - * @param string $class Class path to get - * @return string - */ - public static function getPath($class) - { - if (strncmp('HTMLPurifier', $class, 12) !== 0) { - return false; - } - // Custom implementations - if (strncmp('HTMLPurifier_Language_', $class, 22) === 0) { - $code = str_replace('_', '-', substr($class, 22)); - $file = 'HTMLPurifier/Language/classes/' . $code . '.php'; - } else { - $file = str_replace('_', '/', $class) . '.php'; - } - if (!file_exists(HTMLPURIFIER_PREFIX . '/' . $file)) { - return false; - } - return $file; - } - - /** - * "Pre-registers" our autoloader on the SPL stack. - */ - public static function registerAutoload() - { - $autoload = array('HTMLPurifier_Bootstrap', 'autoload'); - if (($funcs = spl_autoload_functions()) === false) { - spl_autoload_register($autoload); - } elseif (function_exists('spl_autoload_unregister')) { - if (version_compare(PHP_VERSION, '5.3.0', '>=')) { - // prepend flag exists, no need for shenanigans - spl_autoload_register($autoload, true, true); - } else { - $buggy = version_compare(PHP_VERSION, '5.2.11', '<'); - $compat = version_compare(PHP_VERSION, '5.1.2', '<=') && - version_compare(PHP_VERSION, '5.1.0', '>='); - foreach ($funcs as $func) { - if ($buggy && is_array($func)) { - // :TRICKY: There are some compatibility issues and some - // places where we need to error out - $reflector = new ReflectionMethod($func[0], $func[1]); - if (!$reflector->isStatic()) { - throw new Exception( - 'HTML Purifier autoloader registrar is not compatible - with non-static object methods due to PHP Bug #44144; - Please do not use HTMLPurifier.autoload.php (or any - file that includes this file); instead, place the code: - spl_autoload_register(array(\'HTMLPurifier_Bootstrap\', \'autoload\')) - after your own autoloaders.' - ); - } - // Suprisingly, spl_autoload_register supports the - // Class::staticMethod callback format, although call_user_func doesn't - if ($compat) { - $func = implode('::', $func); - } - } - spl_autoload_unregister($func); - } - spl_autoload_register($autoload); - foreach ($funcs as $func) { - spl_autoload_register($func); - } - } - } - } -} - - - - - -/** - * Super-class for definition datatype objects, implements serialization - * functions for the class. - */ -abstract class HTMLPurifier_Definition -{ - - /** - * Has setup() been called yet? - * @type bool - */ - public $setup = false; - - /** - * If true, write out the final definition object to the cache after - * setup. This will be true only if all invocations to get a raw - * definition object are also optimized. This does not cause file - * system thrashing because on subsequent calls the cached object - * is used and any writes to the raw definition object are short - * circuited. See enduser-customize.html for the high-level - * picture. - * @type bool - */ - public $optimized = null; - - /** - * What type of definition is it? - * @type string - */ - public $type; - - /** - * Sets up the definition object into the final form, something - * not done by the constructor - * @param HTMLPurifier_Config $config - */ - abstract protected function doSetup($config); - - /** - * Setup function that aborts if already setup - * @param HTMLPurifier_Config $config - */ - public function setup($config) - { - if ($this->setup) { - return; - } - $this->setup = true; - $this->doSetup($config); - } -} - - - - - -/** - * Defines allowed CSS attributes and what their values are. - * @see HTMLPurifier_HTMLDefinition - */ -class HTMLPurifier_CSSDefinition extends HTMLPurifier_Definition -{ - - public $type = 'CSS'; - - /** - * Assoc array of attribute name to definition object. - * @type HTMLPurifier_AttrDef[] - */ - public $info = array(); - - /** - * Constructs the info array. The meat of this class. - * @param HTMLPurifier_Config $config - */ - protected function doSetup($config) - { - $this->info['text-align'] = new HTMLPurifier_AttrDef_Enum( - array('left', 'right', 'center', 'justify'), - false - ); - - $border_style = - $this->info['border-bottom-style'] = - $this->info['border-right-style'] = - $this->info['border-left-style'] = - $this->info['border-top-style'] = new HTMLPurifier_AttrDef_Enum( - array( - 'none', - 'hidden', - 'dotted', - 'dashed', - 'solid', - 'double', - 'groove', - 'ridge', - 'inset', - 'outset' - ), - false - ); - - $this->info['border-style'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_style); - - $this->info['clear'] = new HTMLPurifier_AttrDef_Enum( - array('none', 'left', 'right', 'both'), - false - ); - $this->info['float'] = new HTMLPurifier_AttrDef_Enum( - array('none', 'left', 'right'), - false - ); - $this->info['font-style'] = new HTMLPurifier_AttrDef_Enum( - array('normal', 'italic', 'oblique'), - false - ); - $this->info['font-variant'] = new HTMLPurifier_AttrDef_Enum( - array('normal', 'small-caps'), - false - ); - - $uri_or_none = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_Enum(array('none')), - new HTMLPurifier_AttrDef_CSS_URI() - ) - ); - - $this->info['list-style-position'] = new HTMLPurifier_AttrDef_Enum( - array('inside', 'outside'), - false - ); - $this->info['list-style-type'] = new HTMLPurifier_AttrDef_Enum( - array( - 'disc', - 'circle', - 'square', - 'decimal', - 'lower-roman', - 'upper-roman', - 'lower-alpha', - 'upper-alpha', - 'none' - ), - false - ); - $this->info['list-style-image'] = $uri_or_none; - - $this->info['list-style'] = new HTMLPurifier_AttrDef_CSS_ListStyle($config); - - $this->info['text-transform'] = new HTMLPurifier_AttrDef_Enum( - array('capitalize', 'uppercase', 'lowercase', 'none'), - false - ); - $this->info['color'] = new HTMLPurifier_AttrDef_CSS_Color(); - - $this->info['background-image'] = $uri_or_none; - $this->info['background-repeat'] = new HTMLPurifier_AttrDef_Enum( - array('repeat', 'repeat-x', 'repeat-y', 'no-repeat') - ); - $this->info['background-attachment'] = new HTMLPurifier_AttrDef_Enum( - array('scroll', 'fixed') - ); - $this->info['background-position'] = new HTMLPurifier_AttrDef_CSS_BackgroundPosition(); - - $border_color = - $this->info['border-top-color'] = - $this->info['border-bottom-color'] = - $this->info['border-left-color'] = - $this->info['border-right-color'] = - $this->info['background-color'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_Enum(array('transparent')), - new HTMLPurifier_AttrDef_CSS_Color() - ) - ); - - $this->info['background'] = new HTMLPurifier_AttrDef_CSS_Background($config); - - $this->info['border-color'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_color); - - $border_width = - $this->info['border-top-width'] = - $this->info['border-bottom-width'] = - $this->info['border-left-width'] = - $this->info['border-right-width'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_Enum(array('thin', 'medium', 'thick')), - new HTMLPurifier_AttrDef_CSS_Length('0') //disallow negative - ) - ); - - $this->info['border-width'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_width); - - $this->info['letter-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_Enum(array('normal')), - new HTMLPurifier_AttrDef_CSS_Length() - ) - ); - - $this->info['word-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_Enum(array('normal')), - new HTMLPurifier_AttrDef_CSS_Length() - ) - ); - - $this->info['font-size'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_Enum( - array( - 'xx-small', - 'x-small', - 'small', - 'medium', - 'large', - 'x-large', - 'xx-large', - 'larger', - 'smaller' - ) - ), - new HTMLPurifier_AttrDef_CSS_Percentage(), - new HTMLPurifier_AttrDef_CSS_Length() - ) - ); - - $this->info['line-height'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_Enum(array('normal')), - new HTMLPurifier_AttrDef_CSS_Number(true), // no negatives - new HTMLPurifier_AttrDef_CSS_Length('0'), - new HTMLPurifier_AttrDef_CSS_Percentage(true) - ) - ); - - $margin = - $this->info['margin-top'] = - $this->info['margin-bottom'] = - $this->info['margin-left'] = - $this->info['margin-right'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_CSS_Length(), - new HTMLPurifier_AttrDef_CSS_Percentage(), - new HTMLPurifier_AttrDef_Enum(array('auto')) - ) - ); - - $this->info['margin'] = new HTMLPurifier_AttrDef_CSS_Multiple($margin); - - // non-negative - $padding = - $this->info['padding-top'] = - $this->info['padding-bottom'] = - $this->info['padding-left'] = - $this->info['padding-right'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_CSS_Length('0'), - new HTMLPurifier_AttrDef_CSS_Percentage(true) - ) - ); - - $this->info['padding'] = new HTMLPurifier_AttrDef_CSS_Multiple($padding); - - $this->info['text-indent'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_CSS_Length(), - new HTMLPurifier_AttrDef_CSS_Percentage() - ) - ); - - $trusted_wh = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_CSS_Length('0'), - new HTMLPurifier_AttrDef_CSS_Percentage(true), - new HTMLPurifier_AttrDef_Enum(array('auto')) - ) - ); - $max = $config->get('CSS.MaxImgLength'); - - $this->info['width'] = - $this->info['height'] = - $max === null ? - $trusted_wh : - new HTMLPurifier_AttrDef_Switch( - 'img', - // For img tags: - new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_CSS_Length('0', $max), - new HTMLPurifier_AttrDef_Enum(array('auto')) - ) - ), - // For everyone else: - $trusted_wh - ); - - $this->info['text-decoration'] = new HTMLPurifier_AttrDef_CSS_TextDecoration(); - - $this->info['font-family'] = new HTMLPurifier_AttrDef_CSS_FontFamily(); - - // this could use specialized code - $this->info['font-weight'] = new HTMLPurifier_AttrDef_Enum( - array( - 'normal', - 'bold', - 'bolder', - 'lighter', - '100', - '200', - '300', - '400', - '500', - '600', - '700', - '800', - '900' - ), - false - ); - - // MUST be called after other font properties, as it references - // a CSSDefinition object - $this->info['font'] = new HTMLPurifier_AttrDef_CSS_Font($config); - - // same here - $this->info['border'] = - $this->info['border-bottom'] = - $this->info['border-top'] = - $this->info['border-left'] = - $this->info['border-right'] = new HTMLPurifier_AttrDef_CSS_Border($config); - - $this->info['border-collapse'] = new HTMLPurifier_AttrDef_Enum( - array('collapse', 'separate') - ); - - $this->info['caption-side'] = new HTMLPurifier_AttrDef_Enum( - array('top', 'bottom') - ); - - $this->info['table-layout'] = new HTMLPurifier_AttrDef_Enum( - array('auto', 'fixed') - ); - - $this->info['vertical-align'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_Enum( - array( - 'baseline', - 'sub', - 'super', - 'top', - 'text-top', - 'middle', - 'bottom', - 'text-bottom' - ) - ), - new HTMLPurifier_AttrDef_CSS_Length(), - new HTMLPurifier_AttrDef_CSS_Percentage() - ) - ); - - $this->info['border-spacing'] = new HTMLPurifier_AttrDef_CSS_Multiple(new HTMLPurifier_AttrDef_CSS_Length(), 2); - - // These CSS properties don't work on many browsers, but we live - // in THE FUTURE! - $this->info['white-space'] = new HTMLPurifier_AttrDef_Enum( - array('nowrap', 'normal', 'pre', 'pre-wrap', 'pre-line') - ); - - if ($config->get('CSS.Proprietary')) { - $this->doSetupProprietary($config); - } - - if ($config->get('CSS.AllowTricky')) { - $this->doSetupTricky($config); - } - - if ($config->get('CSS.Trusted')) { - $this->doSetupTrusted($config); - } - - $allow_important = $config->get('CSS.AllowImportant'); - // wrap all attr-defs with decorator that handles !important - foreach ($this->info as $k => $v) { - $this->info[$k] = new HTMLPurifier_AttrDef_CSS_ImportantDecorator($v, $allow_important); - } - - $this->setupConfigStuff($config); - } - - /** - * @param HTMLPurifier_Config $config - */ - protected function doSetupProprietary($config) - { - // Internet Explorer only scrollbar colors - $this->info['scrollbar-arrow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); - $this->info['scrollbar-base-color'] = new HTMLPurifier_AttrDef_CSS_Color(); - $this->info['scrollbar-darkshadow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); - $this->info['scrollbar-face-color'] = new HTMLPurifier_AttrDef_CSS_Color(); - $this->info['scrollbar-highlight-color'] = new HTMLPurifier_AttrDef_CSS_Color(); - $this->info['scrollbar-shadow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); - - // technically not proprietary, but CSS3, and no one supports it - $this->info['opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); - $this->info['-moz-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); - $this->info['-khtml-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); - - // only opacity, for now - $this->info['filter'] = new HTMLPurifier_AttrDef_CSS_Filter(); - - // more CSS3 - $this->info['page-break-after'] = - $this->info['page-break-before'] = new HTMLPurifier_AttrDef_Enum( - array( - 'auto', - 'always', - 'avoid', - 'left', - 'right' - ) - ); - $this->info['page-break-inside'] = new HTMLPurifier_AttrDef_Enum(array('auto', 'avoid')); - - } - - /** - * @param HTMLPurifier_Config $config - */ - protected function doSetupTricky($config) - { - $this->info['display'] = new HTMLPurifier_AttrDef_Enum( - array( - 'inline', - 'block', - 'list-item', - 'run-in', - 'compact', - 'marker', - 'table', - 'inline-block', - 'inline-table', - 'table-row-group', - 'table-header-group', - 'table-footer-group', - 'table-row', - 'table-column-group', - 'table-column', - 'table-cell', - 'table-caption', - 'none' - ) - ); - $this->info['visibility'] = new HTMLPurifier_AttrDef_Enum( - array('visible', 'hidden', 'collapse') - ); - $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll')); - } - - /** - * @param HTMLPurifier_Config $config - */ - protected function doSetupTrusted($config) - { - $this->info['position'] = new HTMLPurifier_AttrDef_Enum( - array('static', 'relative', 'absolute', 'fixed') - ); - $this->info['top'] = - $this->info['left'] = - $this->info['right'] = - $this->info['bottom'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_CSS_Length(), - new HTMLPurifier_AttrDef_CSS_Percentage(), - new HTMLPurifier_AttrDef_Enum(array('auto')), - ) - ); - $this->info['z-index'] = new HTMLPurifier_AttrDef_CSS_Composite( - array( - new HTMLPurifier_AttrDef_Integer(), - new HTMLPurifier_AttrDef_Enum(array('auto')), - ) - ); - } - - /** - * Performs extra config-based processing. Based off of - * HTMLPurifier_HTMLDefinition. - * @param HTMLPurifier_Config $config - * @todo Refactor duplicate elements into common class (probably using - * composition, not inheritance). - */ - protected function setupConfigStuff($config) - { - // setup allowed elements - $support = "(for information on implementing this, see the " . - "support forums) "; - $allowed_properties = $config->get('CSS.AllowedProperties'); - if ($allowed_properties !== null) { - foreach ($this->info as $name => $d) { - if (!isset($allowed_properties[$name])) { - unset($this->info[$name]); - } - unset($allowed_properties[$name]); - } - // emit errors - foreach ($allowed_properties as $name => $d) { - // :TODO: Is this htmlspecialchars() call really necessary? - $name = htmlspecialchars($name); - trigger_error("Style attribute '$name' is not supported $support", E_USER_WARNING); - } - } - - $forbidden_properties = $config->get('CSS.ForbiddenProperties'); - if ($forbidden_properties !== null) { - foreach ($this->info as $name => $d) { - if (isset($forbidden_properties[$name])) { - unset($this->info[$name]); - } - } - } - } -} - - - - - -/** - * Defines allowed child nodes and validates nodes against it. - */ -abstract class HTMLPurifier_ChildDef -{ - /** - * Type of child definition, usually right-most part of class name lowercase. - * Used occasionally in terms of context. - * @type string - */ - public $type; - - /** - * Indicates whether or not an empty array of children is okay. - * - * This is necessary for redundant checking when changes affecting - * a child node may cause a parent node to now be disallowed. - * @type bool - */ - public $allow_empty; - - /** - * Lookup array of all elements that this definition could possibly allow. - * @type array - */ - public $elements = array(); - - /** - * Get lookup of tag names that should not close this element automatically. - * All other elements will do so. - * @param HTMLPurifier_Config $config HTMLPurifier_Config object - * @return array - */ - public function getAllowedElements($config) - { - return $this->elements; - } - - /** - * Validates nodes according to definition and returns modification. - * - * @param HTMLPurifier_Node[] $children Array of HTMLPurifier_Node - * @param HTMLPurifier_Config $config HTMLPurifier_Config object - * @param HTMLPurifier_Context $context HTMLPurifier_Context object - * @return bool|array true to leave nodes as is, false to remove parent node, array of replacement children - */ - abstract public function validateChildren($children, $config, $context); -} - - - - - -/** - * Configuration object that triggers customizable behavior. - * - * @warning This class is strongly defined: that means that the class - * will fail if an undefined directive is retrieved or set. - * - * @note Many classes that could (although many times don't) use the - * configuration object make it a mandatory parameter. This is - * because a configuration object should always be forwarded, - * otherwise, you run the risk of missing a parameter and then - * being stumped when a configuration directive doesn't work. - * - * @todo Reconsider some of the public member variables - */ -class HTMLPurifier_Config -{ - - /** - * HTML Purifier's version - * @type string - */ - public $version = '4.6.0'; - - /** - * Whether or not to automatically finalize - * the object if a read operation is done. - * @type bool - */ - public $autoFinalize = true; - - // protected member variables - - /** - * Namespace indexed array of serials for specific namespaces. - * @see getSerial() for more info. - * @type string[] - */ - protected $serials = array(); - - /** - * Serial for entire configuration object. - * @type string - */ - protected $serial; - - /** - * Parser for variables. - * @type HTMLPurifier_VarParser_Flexible - */ - protected $parser = null; - - /** - * Reference HTMLPurifier_ConfigSchema for value checking. - * @type HTMLPurifier_ConfigSchema - * @note This is public for introspective purposes. Please don't - * abuse! - */ - public $def; - - /** - * Indexed array of definitions. - * @type HTMLPurifier_Definition[] - */ - protected $definitions; - - /** - * Whether or not config is finalized. - * @type bool - */ - protected $finalized = false; - - /** - * Property list containing configuration directives. - * @type array - */ - protected $plist; - - /** - * Whether or not a set is taking place due to an alias lookup. - * @type bool - */ - private $aliasMode; - - /** - * Set to false if you do not want line and file numbers in errors. - * (useful when unit testing). This will also compress some errors - * and exceptions. - * @type bool - */ - public $chatty = true; - - /** - * Current lock; only gets to this namespace are allowed. - * @type string - */ - private $lock; - - /** - * Constructor - * @param HTMLPurifier_ConfigSchema $definition ConfigSchema that defines - * what directives are allowed. - * @param HTMLPurifier_PropertyList $parent - */ - public function __construct($definition, $parent = null) - { - $parent = $parent ? $parent : $definition->defaultPlist; - $this->plist = new HTMLPurifier_PropertyList($parent); - $this->def = $definition; // keep a copy around for checking - $this->parser = new HTMLPurifier_VarParser_Flexible(); - } - - /** - * Convenience constructor that creates a config object based on a mixed var - * @param mixed $config Variable that defines the state of the config - * object. Can be: a HTMLPurifier_Config() object, - * an array of directives based on loadArray(), - * or a string filename of an ini file. - * @param HTMLPurifier_ConfigSchema $schema Schema object - * @return HTMLPurifier_Config Configured object - */ - public static function create($config, $schema = null) - { - if ($config instanceof HTMLPurifier_Config) { - // pass-through - return $config; - } - if (!$schema) { - $ret = HTMLPurifier_Config::createDefault(); - } else { - $ret = new HTMLPurifier_Config($schema); - } - if (is_string($config)) { - $ret->loadIni($config); - } elseif (is_array($config)) $ret->loadArray($config); - return $ret; - } - - /** - * Creates a new config object that inherits from a previous one. - * @param HTMLPurifier_Config $config Configuration object to inherit from. - * @return HTMLPurifier_Config object with $config as its parent. - */ - public static function inherit(HTMLPurifier_Config $config) - { - return new HTMLPurifier_Config($config->def, $config->plist); - } - - /** - * Convenience constructor that creates a default configuration object. - * @return HTMLPurifier_Config default object. - */ - public static function createDefault() - { - $definition = HTMLPurifier_ConfigSchema::instance(); - $config = new HTMLPurifier_Config($definition); - return $config; - } - - /** - * Retrieves a value from the configuration. - * - * @param string $key String key - * @param mixed $a - * - * @return mixed - */ - public function get($key, $a = null) - { - if ($a !== null) { - $this->triggerError( - "Using deprecated API: use \$config->get('$key.$a') instead", - E_USER_WARNING - ); - $key = "$key.$a"; - } - if (!$this->finalized) { - $this->autoFinalize(); - } - if (!isset($this->def->info[$key])) { - // can't add % due to SimpleTest bug - $this->triggerError( - 'Cannot retrieve value of undefined directive ' . htmlspecialchars($key), - E_USER_WARNING - ); - return; - } - if (isset($this->def->info[$key]->isAlias)) { - $d = $this->def->info[$key]; - $this->triggerError( - 'Cannot get value from aliased directive, use real name ' . $d->key, - E_USER_ERROR - ); - return; - } - if ($this->lock) { - list($ns) = explode('.', $key); - if ($ns !== $this->lock) { - $this->triggerError( - 'Cannot get value of namespace ' . $ns . ' when lock for ' . - $this->lock . - ' is active, this probably indicates a Definition setup method ' . - 'is accessing directives that are not within its namespace', - E_USER_ERROR - ); - return; - } - } - return $this->plist->get($key); - } - - /** - * Retrieves an array of directives to values from a given namespace - * - * @param string $namespace String namespace - * - * @return array - */ - public function getBatch($namespace) - { - if (!$this->finalized) { - $this->autoFinalize(); - } - $full = $this->getAll(); - if (!isset($full[$namespace])) { - $this->triggerError( - 'Cannot retrieve undefined namespace ' . - htmlspecialchars($namespace), - E_USER_WARNING - ); - return; - } - return $full[$namespace]; - } - - /** - * Returns a SHA-1 signature of a segment of the configuration object - * that uniquely identifies that particular configuration - * - * @param string $namespace Namespace to get serial for - * - * @return string - * @note Revision is handled specially and is removed from the batch - * before processing! - */ - public function getBatchSerial($namespace) - { - if (empty($this->serials[$namespace])) { - $batch = $this->getBatch($namespace); - unset($batch['DefinitionRev']); - $this->serials[$namespace] = sha1(serialize($batch)); - } - return $this->serials[$namespace]; - } - - /** - * Returns a SHA-1 signature for the entire configuration object - * that uniquely identifies that particular configuration - * - * @return string - */ - public function getSerial() - { - if (empty($this->serial)) { - $this->serial = sha1(serialize($this->getAll())); - } - return $this->serial; - } - - /** - * Retrieves all directives, organized by namespace - * - * @warning This is a pretty inefficient function, avoid if you can - */ - public function getAll() - { - if (!$this->finalized) { - $this->autoFinalize(); - } - $ret = array(); - foreach ($this->plist->squash() as $name => $value) { - list($ns, $key) = explode('.', $name, 2); - $ret[$ns][$key] = $value; - } - return $ret; - } - - /** - * Sets a value to configuration. - * - * @param string $key key - * @param mixed $value value - * @param mixed $a - */ - public function set($key, $value, $a = null) - { - if (strpos($key, '.') === false) { - $namespace = $key; - $directive = $value; - $value = $a; - $key = "$key.$directive"; - $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE); - } else { - list($namespace) = explode('.', $key); - } - if ($this->isFinalized('Cannot set directive after finalization')) { - return; - } - if (!isset($this->def->info[$key])) { - $this->triggerError( - 'Cannot set undefined directive ' . htmlspecialchars($key) . ' to value', - E_USER_WARNING - ); - return; - } - $def = $this->def->info[$key]; - - if (isset($def->isAlias)) { - if ($this->aliasMode) { - $this->triggerError( - 'Double-aliases not allowed, please fix '. - 'ConfigSchema bug with' . $key, - E_USER_ERROR - ); - return; - } - $this->aliasMode = true; - $this->set($def->key, $value); - $this->aliasMode = false; - $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE); - return; - } - - // Raw type might be negative when using the fully optimized form - // of stdclass, which indicates allow_null == true - $rtype = is_int($def) ? $def : $def->type; - if ($rtype < 0) { - $type = -$rtype; - $allow_null = true; - } else { - $type = $rtype; - $allow_null = isset($def->allow_null); - } - - try { - $value = $this->parser->parse($value, $type, $allow_null); - } catch (HTMLPurifier_VarParserException $e) { - $this->triggerError( - 'Value for ' . $key . ' is of invalid type, should be ' . - HTMLPurifier_VarParser::getTypeName($type), - E_USER_WARNING - ); - return; - } - if (is_string($value) && is_object($def)) { - // resolve value alias if defined - if (isset($def->aliases[$value])) { - $value = $def->aliases[$value]; - } - // check to see if the value is allowed - if (isset($def->allowed) && !isset($def->allowed[$value])) { - $this->triggerError( - 'Value not supported, valid values are: ' . - $this->_listify($def->allowed), - E_USER_WARNING - ); - return; - } - } - $this->plist->set($key, $value); - - // reset definitions if the directives they depend on changed - // this is a very costly process, so it's discouraged - // with finalization - if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') { - $this->definitions[$namespace] = null; - } - - $this->serials[$namespace] = false; - } - - /** - * Convenience function for error reporting - * - * @param array $lookup - * - * @return string - */ - private function _listify($lookup) - { - $list = array(); - foreach ($lookup as $name => $b) { - $list[] = $name; - } - return implode(', ', $list); - } - - /** - * Retrieves object reference to the HTML definition. - * - * @param bool $raw Return a copy that has not been setup yet. Must be - * called before it's been setup, otherwise won't work. - * @param bool $optimized If true, this method may return null, to - * indicate that a cached version of the modified - * definition object is available and no further edits - * are necessary. Consider using - * maybeGetRawHTMLDefinition, which is more explicitly - * named, instead. - * - * @return HTMLPurifier_HTMLDefinition - */ - public function getHTMLDefinition($raw = false, $optimized = false) - { - return $this->getDefinition('HTML', $raw, $optimized); - } - - /** - * Retrieves object reference to the CSS definition - * - * @param bool $raw Return a copy that has not been setup yet. Must be - * called before it's been setup, otherwise won't work. - * @param bool $optimized If true, this method may return null, to - * indicate that a cached version of the modified - * definition object is available and no further edits - * are necessary. Consider using - * maybeGetRawCSSDefinition, which is more explicitly - * named, instead. - * - * @return HTMLPurifier_CSSDefinition - */ - public function getCSSDefinition($raw = false, $optimized = false) - { - return $this->getDefinition('CSS', $raw, $optimized); - } - - /** - * Retrieves object reference to the URI definition - * - * @param bool $raw Return a copy that has not been setup yet. Must be - * called before it's been setup, otherwise won't work. - * @param bool $optimized If true, this method may return null, to - * indicate that a cached version of the modified - * definition object is available and no further edits - * are necessary. Consider using - * maybeGetRawURIDefinition, which is more explicitly - * named, instead. - * - * @return HTMLPurifier_URIDefinition - */ - public function getURIDefinition($raw = false, $optimized = false) - { - return $this->getDefinition('URI', $raw, $optimized); - } - - /** - * Retrieves a definition - * - * @param string $type Type of definition: HTML, CSS, etc - * @param bool $raw Whether or not definition should be returned raw - * @param bool $optimized Only has an effect when $raw is true. Whether - * or not to return null if the result is already present in - * the cache. This is off by default for backwards - * compatibility reasons, but you need to do things this - * way in order to ensure that caching is done properly. - * Check out enduser-customize.html for more details. - * We probably won't ever change this default, as much as the - * maybe semantics is the "right thing to do." - * - * @throws HTMLPurifier_Exception - * @return HTMLPurifier_Definition - */ - public function getDefinition($type, $raw = false, $optimized = false) - { - if ($optimized && !$raw) { - throw new HTMLPurifier_Exception("Cannot set optimized = true when raw = false"); - } - if (!$this->finalized) { - $this->autoFinalize(); - } - // temporarily suspend locks, so we can handle recursive definition calls - $lock = $this->lock; - $this->lock = null; - $factory = HTMLPurifier_DefinitionCacheFactory::instance(); - $cache = $factory->create($type, $this); - $this->lock = $lock; - if (!$raw) { - // full definition - // --------------- - // check if definition is in memory - if (!empty($this->definitions[$type])) { - $def = $this->definitions[$type]; - // check if the definition is setup - if ($def->setup) { - return $def; - } else { - $def->setup($this); - if ($def->optimized) { - $cache->add($def, $this); - } - return $def; - } - } - // check if definition is in cache - $def = $cache->get($this); - if ($def) { - // definition in cache, save to memory and return it - $this->definitions[$type] = $def; - return $def; - } - // initialize it - $def = $this->initDefinition($type); - // set it up - $this->lock = $type; - $def->setup($this); - $this->lock = null; - // save in cache - $cache->add($def, $this); - // return it - return $def; - } else { - // raw definition - // -------------- - // check preconditions - $def = null; - if ($optimized) { - if (is_null($this->get($type . '.DefinitionID'))) { - // fatally error out if definition ID not set - throw new HTMLPurifier_Exception( - "Cannot retrieve raw version without specifying %$type.DefinitionID" - ); - } - } - if (!empty($this->definitions[$type])) { - $def = $this->definitions[$type]; - if ($def->setup && !$optimized) { - $extra = $this->chatty ? - " (try moving this code block earlier in your initialization)" : - ""; - throw new HTMLPurifier_Exception( - "Cannot retrieve raw definition after it has already been setup" . - $extra - ); - } - if ($def->optimized === null) { - $extra = $this->chatty ? " (try flushing your cache)" : ""; - throw new HTMLPurifier_Exception( - "Optimization status of definition is unknown" . $extra - ); - } - if ($def->optimized !== $optimized) { - $msg = $optimized ? "optimized" : "unoptimized"; - $extra = $this->chatty ? - " (this backtrace is for the first inconsistent call, which was for a $msg raw definition)" - : ""; - throw new HTMLPurifier_Exception( - "Inconsistent use of optimized and unoptimized raw definition retrievals" . $extra - ); - } - } - // check if definition was in memory - if ($def) { - if ($def->setup) { - // invariant: $optimized === true (checked above) - return null; - } else { - return $def; - } - } - // if optimized, check if definition was in cache - // (because we do the memory check first, this formulation - // is prone to cache slamming, but I think - // guaranteeing that either /all/ of the raw - // setup code or /none/ of it is run is more important.) - if ($optimized) { - // This code path only gets run once; once we put - // something in $definitions (which is guaranteed by the - // trailing code), we always short-circuit above. - $def = $cache->get($this); - if ($def) { - // save the full definition for later, but don't - // return it yet - $this->definitions[$type] = $def; - return null; - } - } - // check invariants for creation - if (!$optimized) { - if (!is_null($this->get($type . '.DefinitionID'))) { - if ($this->chatty) { - $this->triggerError( - 'Due to a documentation error in previous version of HTML Purifier, your ' . - 'definitions are not being cached. If this is OK, you can remove the ' . - '%$type.DefinitionRev and %$type.DefinitionID declaration. Otherwise, ' . - 'modify your code to use maybeGetRawDefinition, and test if the returned ' . - 'value is null before making any edits (if it is null, that means that a ' . - 'cached version is available, and no raw operations are necessary). See ' . - '' . - 'Customize for more details', - E_USER_WARNING - ); - } else { - $this->triggerError( - "Useless DefinitionID declaration", - E_USER_WARNING - ); - } - } - } - // initialize it - $def = $this->initDefinition($type); - $def->optimized = $optimized; - return $def; - } - throw new HTMLPurifier_Exception("The impossible happened!"); - } - - /** - * Initialise definition - * - * @param string $type What type of definition to create - * - * @return HTMLPurifier_CSSDefinition|HTMLPurifier_HTMLDefinition|HTMLPurifier_URIDefinition - * @throws HTMLPurifier_Exception - */ - private function initDefinition($type) - { - // quick checks failed, let's create the object - if ($type == 'HTML') { - $def = new HTMLPurifier_HTMLDefinition(); - } elseif ($type == 'CSS') { - $def = new HTMLPurifier_CSSDefinition(); - } elseif ($type == 'URI') { - $def = new HTMLPurifier_URIDefinition(); - } else { - throw new HTMLPurifier_Exception( - "Definition of $type type not supported" - ); - } - $this->definitions[$type] = $def; - return $def; - } - - public function maybeGetRawDefinition($name) - { - return $this->getDefinition($name, true, true); - } - - public function maybeGetRawHTMLDefinition() - { - return $this->getDefinition('HTML', true, true); - } - - public function maybeGetRawCSSDefinition() - { - return $this->getDefinition('CSS', true, true); - } - - public function maybeGetRawURIDefinition() - { - return $this->getDefinition('URI', true, true); - } - - /** - * Loads configuration values from an array with the following structure: - * Namespace.Directive => Value - * - * @param array $config_array Configuration associative array - */ - public function loadArray($config_array) - { - if ($this->isFinalized('Cannot load directives after finalization')) { - return; - } - foreach ($config_array as $key => $value) { - $key = str_replace('_', '.', $key); - if (strpos($key, '.') !== false) { - $this->set($key, $value); - } else { - $namespace = $key; - $namespace_values = $value; - foreach ($namespace_values as $directive => $value2) { - $this->set($namespace .'.'. $directive, $value2); - } - } - } - } - - /** - * Returns a list of array(namespace, directive) for all directives - * that are allowed in a web-form context as per an allowed - * namespaces/directives list. - * - * @param array $allowed List of allowed namespaces/directives - * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy - * - * @return array - */ - public static function getAllowedDirectivesForForm($allowed, $schema = null) - { - if (!$schema) { - $schema = HTMLPurifier_ConfigSchema::instance(); - } - if ($allowed !== true) { - if (is_string($allowed)) { - $allowed = array($allowed); - } - $allowed_ns = array(); - $allowed_directives = array(); - $blacklisted_directives = array(); - foreach ($allowed as $ns_or_directive) { - if (strpos($ns_or_directive, '.') !== false) { - // directive - if ($ns_or_directive[0] == '-') { - $blacklisted_directives[substr($ns_or_directive, 1)] = true; - } else { - $allowed_directives[$ns_or_directive] = true; - } - } else { - // namespace - $allowed_ns[$ns_or_directive] = true; - } - } - } - $ret = array(); - foreach ($schema->info as $key => $def) { - list($ns, $directive) = explode('.', $key, 2); - if ($allowed !== true) { - if (isset($blacklisted_directives["$ns.$directive"])) { - continue; - } - if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) { - continue; - } - } - if (isset($def->isAlias)) { - continue; - } - if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') { - continue; - } - $ret[] = array($ns, $directive); - } - return $ret; - } - - /** - * Loads configuration values from $_GET/$_POST that were posted - * via ConfigForm - * - * @param array $array $_GET or $_POST array to import - * @param string|bool $index Index/name that the config variables are in - * @param array|bool $allowed List of allowed namespaces/directives - * @param bool $mq_fix Boolean whether or not to enable magic quotes fix - * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy - * - * @return mixed - */ - public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) - { - $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema); - $config = HTMLPurifier_Config::create($ret, $schema); - return $config; - } - - /** - * Merges in configuration values from $_GET/$_POST to object. NOT STATIC. - * - * @param array $array $_GET or $_POST array to import - * @param string|bool $index Index/name that the config variables are in - * @param array|bool $allowed List of allowed namespaces/directives - * @param bool $mq_fix Boolean whether or not to enable magic quotes fix - */ - public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) - { - $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def); - $this->loadArray($ret); - } - - /** - * Prepares an array from a form into something usable for the more - * strict parts of HTMLPurifier_Config - * - * @param array $array $_GET or $_POST array to import - * @param string|bool $index Index/name that the config variables are in - * @param array|bool $allowed List of allowed namespaces/directives - * @param bool $mq_fix Boolean whether or not to enable magic quotes fix - * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy - * - * @return array - */ - public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) - { - if ($index !== false) { - $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array(); - } - $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc(); - - $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema); - $ret = array(); - foreach ($allowed as $key) { - list($ns, $directive) = $key; - $skey = "$ns.$directive"; - if (!empty($array["Null_$skey"])) { - $ret[$ns][$directive] = null; - continue; - } - if (!isset($array[$skey])) { - continue; - } - $value = $mq ? stripslashes($array[$skey]) : $array[$skey]; - $ret[$ns][$directive] = $value; - } - return $ret; - } - - /** - * Loads configuration values from an ini file - * - * @param string $filename Name of ini file - */ - public function loadIni($filename) - { - if ($this->isFinalized('Cannot load directives after finalization')) { - return; - } - $array = parse_ini_file($filename, true); - $this->loadArray($array); - } - - /** - * Checks whether or not the configuration object is finalized. - * - * @param string|bool $error String error message, or false for no error - * - * @return bool - */ - public function isFinalized($error = false) - { - if ($this->finalized && $error) { - $this->triggerError($error, E_USER_ERROR); - } - return $this->finalized; - } - - /** - * Finalizes configuration only if auto finalize is on and not - * already finalized - */ - public function autoFinalize() - { - if ($this->autoFinalize) { - $this->finalize(); - } else { - $this->plist->squash(true); - } - } - - /** - * Finalizes a configuration object, prohibiting further change - */ - public function finalize() - { - $this->finalized = true; - $this->parser = null; - } - - /** - * Produces a nicely formatted error message by supplying the - * stack frame information OUTSIDE of HTMLPurifier_Config. - * - * @param string $msg An error message - * @param int $no An error number - */ - protected function triggerError($msg, $no) - { - // determine previous stack frame - $extra = ''; - if ($this->chatty) { - $trace = debug_backtrace(); - // zip(tail(trace), trace) -- but PHP is not Haskell har har - for ($i = 0, $c = count($trace); $i < $c - 1; $i++) { - // XXX this is not correct on some versions of HTML Purifier - if ($trace[$i + 1]['class'] === 'HTMLPurifier_Config') { - continue; - } - $frame = $trace[$i]; - $extra = " invoked on line {$frame['line']} in file {$frame['file']}"; - break; - } - } - trigger_error($msg . $extra, $no); - } - - /** - * Returns a serialized form of the configuration object that can - * be reconstituted. - * - * @return string - */ - public function serialize() - { - $this->getDefinition('HTML'); - $this->getDefinition('CSS'); - $this->getDefinition('URI'); - return serialize($this); - } - -} - - - - - -/** - * Configuration definition, defines directives and their defaults. - */ -class HTMLPurifier_ConfigSchema -{ - /** - * Defaults of the directives and namespaces. - * @type array - * @note This shares the exact same structure as HTMLPurifier_Config::$conf - */ - public $defaults = array(); - - /** - * The default property list. Do not edit this property list. - * @type array - */ - public $defaultPlist; - - /** - * Definition of the directives. - * The structure of this is: - * - * array( - * 'Namespace' => array( - * 'Directive' => new stdclass(), - * ) - * ) - * - * The stdclass may have the following properties: - * - * - If isAlias isn't set: - * - type: Integer type of directive, see HTMLPurifier_VarParser for definitions - * - allow_null: If set, this directive allows null values - * - aliases: If set, an associative array of value aliases to real values - * - allowed: If set, a lookup array of allowed (string) values - * - If isAlias is set: - * - namespace: Namespace this directive aliases to - * - name: Directive name this directive aliases to - * - * In certain degenerate cases, stdclass will actually be an integer. In - * that case, the value is equivalent to an stdclass with the type - * property set to the integer. If the integer is negative, type is - * equal to the absolute value of integer, and allow_null is true. - * - * This class is friendly with HTMLPurifier_Config. If you need introspection - * about the schema, you're better of using the ConfigSchema_Interchange, - * which uses more memory but has much richer information. - * @type array - */ - public $info = array(); - - /** - * Application-wide singleton - * @type HTMLPurifier_ConfigSchema - */ - protected static $singleton; - - public function __construct() - { - $this->defaultPlist = new HTMLPurifier_PropertyList(); - } - - /** - * Unserializes the default ConfigSchema. - * @return HTMLPurifier_ConfigSchema - */ - public static function makeFromSerial() - { - $contents = file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema.ser'); - $r = unserialize($contents); - if (!$r) { - $hash = sha1($contents); - trigger_error("Unserialization of configuration schema failed, sha1 of file was $hash", E_USER_ERROR); - } - return $r; - } - - /** - * Retrieves an instance of the application-wide configuration definition. - * @param HTMLPurifier_ConfigSchema $prototype - * @return HTMLPurifier_ConfigSchema - */ - public static function instance($prototype = null) - { - if ($prototype !== null) { - HTMLPurifier_ConfigSchema::$singleton = $prototype; - } elseif (HTMLPurifier_ConfigSchema::$singleton === null || $prototype === true) { - HTMLPurifier_ConfigSchema::$singleton = HTMLPurifier_ConfigSchema::makeFromSerial(); - } - return HTMLPurifier_ConfigSchema::$singleton; - } - - /** - * Defines a directive for configuration - * @warning Will fail of directive's namespace is defined. - * @warning This method's signature is slightly different from the legacy - * define() static method! Beware! - * @param string $key Name of directive - * @param mixed $default Default value of directive - * @param string $type Allowed type of the directive. See - * HTMLPurifier_DirectiveDef::$type for allowed values - * @param bool $allow_null Whether or not to allow null values - */ - public function add($key, $default, $type, $allow_null) - { - $obj = new stdclass(); - $obj->type = is_int($type) ? $type : HTMLPurifier_VarParser::$types[$type]; - if ($allow_null) { - $obj->allow_null = true; - } - $this->info[$key] = $obj; - $this->defaults[$key] = $default; - $this->defaultPlist->set($key, $default); - } - - /** - * Defines a directive value alias. - * - * Directive value aliases are convenient for developers because it lets - * them set a directive to several values and get the same result. - * @param string $key Name of Directive - * @param array $aliases Hash of aliased values to the real alias - */ - public function addValueAliases($key, $aliases) - { - if (!isset($this->info[$key]->aliases)) { - $this->info[$key]->aliases = array(); - } - foreach ($aliases as $alias => $real) { - $this->info[$key]->aliases[$alias] = $real; - } - } - - /** - * Defines a set of allowed values for a directive. - * @warning This is slightly different from the corresponding static - * method definition. - * @param string $key Name of directive - * @param array $allowed Lookup array of allowed values - */ - public function addAllowedValues($key, $allowed) - { - $this->info[$key]->allowed = $allowed; - } - - /** - * Defines a directive alias for backwards compatibility - * @param string $key Directive that will be aliased - * @param string $new_key Directive that the alias will be to - */ - public function addAlias($key, $new_key) - { - $obj = new stdclass; - $obj->key = $new_key; - $obj->isAlias = true; - $this->info[$key] = $obj; - } - - /** - * Replaces any stdclass that only has the type property with type integer. - */ - public function postProcess() - { - foreach ($this->info as $key => $v) { - if (count((array) $v) == 1) { - $this->info[$key] = $v->type; - } elseif (count((array) $v) == 2 && isset($v->allow_null)) { - $this->info[$key] = -$v->type; - } - } - } -} - - - - - -/** - * @todo Unit test - */ -class HTMLPurifier_ContentSets -{ - - /** - * List of content set strings (pipe separators) indexed by name. - * @type array - */ - public $info = array(); - - /** - * List of content set lookups (element => true) indexed by name. - * @type array - * @note This is in HTMLPurifier_HTMLDefinition->info_content_sets - */ - public $lookup = array(); - - /** - * Synchronized list of defined content sets (keys of info). - * @type array - */ - protected $keys = array(); - /** - * Synchronized list of defined content values (values of info). - * @type array - */ - protected $values = array(); - - /** - * Merges in module's content sets, expands identifiers in the content - * sets and populates the keys, values and lookup member variables. - * @param HTMLPurifier_HTMLModule[] $modules List of HTMLPurifier_HTMLModule - */ - public function __construct($modules) - { - if (!is_array($modules)) { - $modules = array($modules); - } - // populate content_sets based on module hints - // sorry, no way of overloading - foreach ($modules as $module) { - foreach ($module->content_sets as $key => $value) { - $temp = $this->convertToLookup($value); - if (isset($this->lookup[$key])) { - // add it into the existing content set - $this->lookup[$key] = array_merge($this->lookup[$key], $temp); - } else { - $this->lookup[$key] = $temp; - } - } - } - $old_lookup = false; - while ($old_lookup !== $this->lookup) { - $old_lookup = $this->lookup; - foreach ($this->lookup as $i => $set) { - $add = array(); - foreach ($set as $element => $x) { - if (isset($this->lookup[$element])) { - $add += $this->lookup[$element]; - unset($this->lookup[$i][$element]); - } - } - $this->lookup[$i] += $add; - } - } - - foreach ($this->lookup as $key => $lookup) { - $this->info[$key] = implode(' | ', array_keys($lookup)); - } - $this->keys = array_keys($this->info); - $this->values = array_values($this->info); - } - - /** - * Accepts a definition; generates and assigns a ChildDef for it - * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef reference - * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef - */ - public function generateChildDef(&$def, $module) - { - if (!empty($def->child)) { // already done! - return; - } - $content_model = $def->content_model; - if (is_string($content_model)) { - // Assume that $this->keys is alphanumeric - $def->content_model = preg_replace_callback( - '/\b(' . implode('|', $this->keys) . ')\b/', - array($this, 'generateChildDefCallback'), - $content_model - ); - //$def->content_model = str_replace( - // $this->keys, $this->values, $content_model); - } - $def->child = $this->getChildDef($def, $module); - } - - public function generateChildDefCallback($matches) - { - return $this->info[$matches[0]]; - } - - /** - * Instantiates a ChildDef based on content_model and content_model_type - * member variables in HTMLPurifier_ElementDef - * @note This will also defer to modules for custom HTMLPurifier_ChildDef - * subclasses that need content set expansion - * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef to have ChildDef extracted - * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef - * @return HTMLPurifier_ChildDef corresponding to ElementDef - */ - public function getChildDef($def, $module) - { - $value = $def->content_model; - if (is_object($value)) { - trigger_error( - 'Literal object child definitions should be stored in '. - 'ElementDef->child not ElementDef->content_model', - E_USER_NOTICE - ); - return $value; - } - switch ($def->content_model_type) { - case 'required': - return new HTMLPurifier_ChildDef_Required($value); - case 'optional': - return new HTMLPurifier_ChildDef_Optional($value); - case 'empty': - return new HTMLPurifier_ChildDef_Empty(); - case 'custom': - return new HTMLPurifier_ChildDef_Custom($value); - } - // defer to its module - $return = false; - if ($module->defines_child_def) { // save a func call - $return = $module->getChildDef($def); - } - if ($return !== false) { - return $return; - } - // error-out - trigger_error( - 'Could not determine which ChildDef class to instantiate', - E_USER_ERROR - ); - return false; - } - - /** - * Converts a string list of elements separated by pipes into - * a lookup array. - * @param string $string List of elements - * @return array Lookup array of elements - */ - protected function convertToLookup($string) - { - $array = explode('|', str_replace(' ', '', $string)); - $ret = array(); - foreach ($array as $k) { - $ret[$k] = true; - } - return $ret; - } -} - - - - - -/** - * Registry object that contains information about the current context. - * @warning Is a bit buggy when variables are set to null: it thinks - * they don't exist! So use false instead, please. - * @note Since the variables Context deals with may not be objects, - * references are very important here! Do not remove! - */ -class HTMLPurifier_Context -{ - - /** - * Private array that stores the references. - * @type array - */ - private $_storage = array(); - - /** - * Registers a variable into the context. - * @param string $name String name - * @param mixed $ref Reference to variable to be registered - */ - public function register($name, &$ref) - { - if (array_key_exists($name, $this->_storage)) { - trigger_error( - "Name $name produces collision, cannot re-register", - E_USER_ERROR - ); - return; - } - $this->_storage[$name] =& $ref; - } - - /** - * Retrieves a variable reference from the context. - * @param string $name String name - * @param bool $ignore_error Boolean whether or not to ignore error - * @return mixed - */ - public function &get($name, $ignore_error = false) - { - if (!array_key_exists($name, $this->_storage)) { - if (!$ignore_error) { - trigger_error( - "Attempted to retrieve non-existent variable $name", - E_USER_ERROR - ); - } - $var = null; // so we can return by reference - return $var; - } - return $this->_storage[$name]; - } - - /** - * Destroys a variable in the context. - * @param string $name String name - */ - public function destroy($name) - { - if (!array_key_exists($name, $this->_storage)) { - trigger_error( - "Attempted to destroy non-existent variable $name", - E_USER_ERROR - ); - return; - } - unset($this->_storage[$name]); - } - - /** - * Checks whether or not the variable exists. - * @param string $name String name - * @return bool - */ - public function exists($name) - { - return array_key_exists($name, $this->_storage); - } - - /** - * Loads a series of variables from an associative array - * @param array $context_array Assoc array of variables to load - */ - public function loadArray($context_array) - { - foreach ($context_array as $key => $discard) { - $this->register($key, $context_array[$key]); - } - } -} - - - - - -/** - * Abstract class representing Definition cache managers that implements - * useful common methods and is a factory. - * @todo Create a separate maintenance file advanced users can use to - * cache their custom HTMLDefinition, which can be loaded - * via a configuration directive - * @todo Implement memcached - */ -abstract class HTMLPurifier_DefinitionCache -{ - /** - * @type string - */ - public $type; - - /** - * @param string $type Type of definition objects this instance of the - * cache will handle. - */ - public function __construct($type) - { - $this->type = $type; - } - - /** - * Generates a unique identifier for a particular configuration - * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config - * @return string - */ - public function generateKey($config) - { - return $config->version . ',' . // possibly replace with function calls - $config->getBatchSerial($this->type) . ',' . - $config->get($this->type . '.DefinitionRev'); - } - - /** - * Tests whether or not a key is old with respect to the configuration's - * version and revision number. - * @param string $key Key to test - * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config to test against - * @return bool - */ - public function isOld($key, $config) - { - if (substr_count($key, ',') < 2) { - return true; - } - list($version, $hash, $revision) = explode(',', $key, 3); - $compare = version_compare($version, $config->version); - // version mismatch, is always old - if ($compare != 0) { - return true; - } - // versions match, ids match, check revision number - if ($hash == $config->getBatchSerial($this->type) && - $revision < $config->get($this->type . '.DefinitionRev')) { - return true; - } - return false; - } - - /** - * Checks if a definition's type jives with the cache's type - * @note Throws an error on failure - * @param HTMLPurifier_Definition $def Definition object to check - * @return bool true if good, false if not - */ - public function checkDefType($def) - { - if ($def->type !== $this->type) { - trigger_error("Cannot use definition of type {$def->type} in cache for {$this->type}"); - return false; - } - return true; - } - - /** - * Adds a definition object to the cache - * @param HTMLPurifier_Definition $def - * @param HTMLPurifier_Config $config - */ - abstract public function add($def, $config); - - /** - * Unconditionally saves a definition object to the cache - * @param HTMLPurifier_Definition $def - * @param HTMLPurifier_Config $config - */ - abstract public function set($def, $config); - - /** - * Replace an object in the cache - * @param HTMLPurifier_Definition $def - * @param HTMLPurifier_Config $config - */ - abstract public function replace($def, $config); - - /** - * Retrieves a definition object from the cache - * @param HTMLPurifier_Config $config - */ - abstract public function get($config); - - /** - * Removes a definition object to the cache - * @param HTMLPurifier_Config $config - */ - abstract public function remove($config); - - /** - * Clears all objects from cache - * @param HTMLPurifier_Config $config - */ - abstract public function flush($config); - - /** - * Clears all expired (older version or revision) objects from cache - * @note Be carefuly implementing this method as flush. Flush must - * not interfere with other Definition types, and cleanup() - * should not be repeatedly called by userland code. - * @param HTMLPurifier_Config $config - */ - abstract public function cleanup($config); -} - - - - - -/** - * Responsible for creating definition caches. - */ -class HTMLPurifier_DefinitionCacheFactory -{ - /** - * @type array - */ - protected $caches = array('Serializer' => array()); - - /** - * @type array - */ - protected $implementations = array(); - - /** - * @type HTMLPurifier_DefinitionCache_Decorator[] - */ - protected $decorators = array(); - - /** - * Initialize default decorators - */ - public function setup() - { - $this->addDecorator('Cleanup'); - } - - /** - * Retrieves an instance of global definition cache factory. - * @param HTMLPurifier_DefinitionCacheFactory $prototype - * @return HTMLPurifier_DefinitionCacheFactory - */ - public static function instance($prototype = null) - { - static $instance; - if ($prototype !== null) { - $instance = $prototype; - } elseif ($instance === null || $prototype === true) { - $instance = new HTMLPurifier_DefinitionCacheFactory(); - $instance->setup(); - } - return $instance; - } - - /** - * Registers a new definition cache object - * @param string $short Short name of cache object, for reference - * @param string $long Full class name of cache object, for construction - */ - public function register($short, $long) - { - $this->implementations[$short] = $long; - } - - /** - * Factory method that creates a cache object based on configuration - * @param string $type Name of definitions handled by cache - * @param HTMLPurifier_Config $config Config instance - * @return mixed - */ - public function create($type, $config) - { - $method = $config->get('Cache.DefinitionImpl'); - if ($method === null) { - return new HTMLPurifier_DefinitionCache_Null($type); - } - if (!empty($this->caches[$method][$type])) { - return $this->caches[$method][$type]; - } - if (isset($this->implementations[$method]) && - class_exists($class = $this->implementations[$method], false)) { - $cache = new $class($type); - } else { - if ($method != 'Serializer') { - trigger_error("Unrecognized DefinitionCache $method, using Serializer instead", E_USER_WARNING); - } - $cache = new HTMLPurifier_DefinitionCache_Serializer($type); - } - foreach ($this->decorators as $decorator) { - $new_cache = $decorator->decorate($cache); - // prevent infinite recursion in PHP 4 - unset($cache); - $cache = $new_cache; - } - $this->caches[$method][$type] = $cache; - return $this->caches[$method][$type]; - } - - /** - * Registers a decorator to add to all new cache objects - * @param HTMLPurifier_DefinitionCache_Decorator|string $decorator An instance or the name of a decorator - */ - public function addDecorator($decorator) - { - if (is_string($decorator)) { - $class = "HTMLPurifier_DefinitionCache_Decorator_$decorator"; - $decorator = new $class; - } - $this->decorators[$decorator->name] = $decorator; - } -} - - - - - -/** - * Represents a document type, contains information on which modules - * need to be loaded. - * @note This class is inspected by Printer_HTMLDefinition->renderDoctype. - * If structure changes, please update that function. - */ -class HTMLPurifier_Doctype -{ - /** - * Full name of doctype - * @type string - */ - public $name; - - /** - * List of standard modules (string identifiers or literal objects) - * that this doctype uses - * @type array - */ - public $modules = array(); - - /** - * List of modules to use for tidying up code - * @type array - */ - public $tidyModules = array(); - - /** - * Is the language derived from XML (i.e. XHTML)? - * @type bool - */ - public $xml = true; - - /** - * List of aliases for this doctype - * @type array - */ - public $aliases = array(); - - /** - * Public DTD identifier - * @type string - */ - public $dtdPublic; - - /** - * System DTD identifier - * @type string - */ - public $dtdSystem; - - public function __construct( - $name = null, - $xml = true, - $modules = array(), - $tidyModules = array(), - $aliases = array(), - $dtd_public = null, - $dtd_system = null - ) { - $this->name = $name; - $this->xml = $xml; - $this->modules = $modules; - $this->tidyModules = $tidyModules; - $this->aliases = $aliases; - $this->dtdPublic = $dtd_public; - $this->dtdSystem = $dtd_system; - } -} - - - - - -class HTMLPurifier_DoctypeRegistry -{ - - /** - * Hash of doctype names to doctype objects. - * @type array - */ - protected $doctypes; - - /** - * Lookup table of aliases to real doctype names. - * @type array - */ - protected $aliases; - - /** - * Registers a doctype to the registry - * @note Accepts a fully-formed doctype object, or the - * parameters for constructing a doctype object - * @param string $doctype Name of doctype or literal doctype object - * @param bool $xml - * @param array $modules Modules doctype will load - * @param array $tidy_modules Modules doctype will load for certain modes - * @param array $aliases Alias names for doctype - * @param string $dtd_public - * @param string $dtd_system - * @return HTMLPurifier_Doctype Editable registered doctype - */ - public function register( - $doctype, - $xml = true, - $modules = array(), - $tidy_modules = array(), - $aliases = array(), - $dtd_public = null, - $dtd_system = null - ) { - if (!is_array($modules)) { - $modules = array($modules); - } - if (!is_array($tidy_modules)) { - $tidy_modules = array($tidy_modules); - } - if (!is_array($aliases)) { - $aliases = array($aliases); - } - if (!is_object($doctype)) { - $doctype = new HTMLPurifier_Doctype( - $doctype, - $xml, - $modules, - $tidy_modules, - $aliases, - $dtd_public, - $dtd_system - ); - } - $this->doctypes[$doctype->name] = $doctype; - $name = $doctype->name; - // hookup aliases - foreach ($doctype->aliases as $alias) { - if (isset($this->doctypes[$alias])) { - continue; - } - $this->aliases[$alias] = $name; - } - // remove old aliases - if (isset($this->aliases[$name])) { - unset($this->aliases[$name]); - } - return $doctype; - } - - /** - * Retrieves reference to a doctype of a certain name - * @note This function resolves aliases - * @note When possible, use the more fully-featured make() - * @param string $doctype Name of doctype - * @return HTMLPurifier_Doctype Editable doctype object - */ - public function get($doctype) - { - if (isset($this->aliases[$doctype])) { - $doctype = $this->aliases[$doctype]; - } - if (!isset($this->doctypes[$doctype])) { - trigger_error('Doctype ' . htmlspecialchars($doctype) . ' does not exist', E_USER_ERROR); - $anon = new HTMLPurifier_Doctype($doctype); - return $anon; - } - return $this->doctypes[$doctype]; - } - - /** - * Creates a doctype based on a configuration object, - * will perform initialization on the doctype - * @note Use this function to get a copy of doctype that config - * can hold on to (this is necessary in order to tell - * Generator whether or not the current document is XML - * based or not). - * @param HTMLPurifier_Config $config - * @return HTMLPurifier_Doctype - */ - public function make($config) - { - return clone $this->get($this->getDoctypeFromConfig($config)); - } - - /** - * Retrieves the doctype from the configuration object - * @param HTMLPurifier_Config $config - * @return string - */ - public function getDoctypeFromConfig($config) - { - // recommended test - $doctype = $config->get('HTML.Doctype'); - if (!empty($doctype)) { - return $doctype; - } - $doctype = $config->get('HTML.CustomDoctype'); - if (!empty($doctype)) { - return $doctype; - } - // backwards-compatibility - if ($config->get('HTML.XHTML')) { - $doctype = 'XHTML 1.0'; - } else { - $doctype = 'HTML 4.01'; - } - if ($config->get('HTML.Strict')) { - $doctype .= ' Strict'; - } else { - $doctype .= ' Transitional'; - } - return $doctype; - } -} - - - - - -/** - * Structure that stores an HTML element definition. Used by - * HTMLPurifier_HTMLDefinition and HTMLPurifier_HTMLModule. - * @note This class is inspected by HTMLPurifier_Printer_HTMLDefinition. - * Please update that class too. - * @warning If you add new properties to this class, you MUST update - * the mergeIn() method. - */ -class HTMLPurifier_ElementDef -{ - /** - * Does the definition work by itself, or is it created solely - * for the purpose of merging into another definition? - * @type bool - */ - public $standalone = true; - - /** - * Associative array of attribute name to HTMLPurifier_AttrDef. - * @type array - * @note Before being processed by HTMLPurifier_AttrCollections - * when modules are finalized during - * HTMLPurifier_HTMLDefinition->setup(), this array may also - * contain an array at index 0 that indicates which attribute - * collections to load into the full array. It may also - * contain string indentifiers in lieu of HTMLPurifier_AttrDef, - * see HTMLPurifier_AttrTypes on how they are expanded during - * HTMLPurifier_HTMLDefinition->setup() processing. - */ - public $attr = array(); - - // XXX: Design note: currently, it's not possible to override - // previously defined AttrTransforms without messing around with - // the final generated config. This is by design; a previous version - // used an associated list of attr_transform, but it was extremely - // easy to accidentally override other attribute transforms by - // forgetting to specify an index (and just using 0.) While we - // could check this by checking the index number and complaining, - // there is a second problem which is that it is not at all easy to - // tell when something is getting overridden. Combine this with a - // codebase where this isn't really being used, and it's perfect for - // nuking. - - /** - * List of tags HTMLPurifier_AttrTransform to be done before validation. - * @type array - */ - public $attr_transform_pre = array(); - - /** - * List of tags HTMLPurifier_AttrTransform to be done after validation. - * @type array - */ - public $attr_transform_post = array(); - - /** - * HTMLPurifier_ChildDef of this tag. - * @type HTMLPurifier_ChildDef - */ - public $child; - - /** - * Abstract string representation of internal ChildDef rules. - * @see HTMLPurifier_ContentSets for how this is parsed and then transformed - * into an HTMLPurifier_ChildDef. - * @warning This is a temporary variable that is not available after - * being processed by HTMLDefinition - * @type string - */ - public $content_model; - - /** - * Value of $child->type, used to determine which ChildDef to use, - * used in combination with $content_model. - * @warning This must be lowercase - * @warning This is a temporary variable that is not available after - * being processed by HTMLDefinition - * @type string - */ - public $content_model_type; - - /** - * Does the element have a content model (#PCDATA | Inline)*? This - * is important for chameleon ins and del processing in - * HTMLPurifier_ChildDef_Chameleon. Dynamically set: modules don't - * have to worry about this one. - * @type bool - */ - public $descendants_are_inline = false; - - /** - * List of the names of required attributes this element has. - * Dynamically populated by HTMLPurifier_HTMLDefinition::getElement() - * @type array - */ - public $required_attr = array(); - - /** - * Lookup table of tags excluded from all descendants of this tag. - * @type array - * @note SGML permits exclusions for all descendants, but this is - * not possible with DTDs or XML Schemas. W3C has elected to - * use complicated compositions of content_models to simulate - * exclusion for children, but we go the simpler, SGML-style - * route of flat-out exclusions, which correctly apply to - * all descendants and not just children. Note that the XHTML - * Modularization Abstract Modules are blithely unaware of such - * distinctions. - */ - public $excludes = array(); - - /** - * This tag is explicitly auto-closed by the following tags. - * @type array - */ - public $autoclose = array(); - - /** - * If a foreign element is found in this element, test if it is - * allowed by this sub-element; if it is, instead of closing the - * current element, place it inside this element. - * @type string - */ - public $wrap; - - /** - * Whether or not this is a formatting element affected by the - * "Active Formatting Elements" algorithm. - * @type bool - */ - public $formatting; - - /** - * Low-level factory constructor for creating new standalone element defs - */ - public static function create($content_model, $content_model_type, $attr) - { - $def = new HTMLPurifier_ElementDef(); - $def->content_model = $content_model; - $def->content_model_type = $content_model_type; - $def->attr = $attr; - return $def; - } - - /** - * Merges the values of another element definition into this one. - * Values from the new element def take precedence if a value is - * not mergeable. - * @param HTMLPurifier_ElementDef $def - */ - public function mergeIn($def) - { - // later keys takes precedence - foreach ($def->attr as $k => $v) { - if ($k === 0) { - // merge in the includes - // sorry, no way to override an include - foreach ($v as $v2) { - $this->attr[0][] = $v2; - } - continue; - } - if ($v === false) { - if (isset($this->attr[$k])) { - unset($this->attr[$k]); - } - continue; - } - $this->attr[$k] = $v; - } - $this->_mergeAssocArray($this->excludes, $def->excludes); - $this->attr_transform_pre = array_merge($this->attr_transform_pre, $def->attr_transform_pre); - $this->attr_transform_post = array_merge($this->attr_transform_post, $def->attr_transform_post); - - if (!empty($def->content_model)) { - $this->content_model = - str_replace("#SUPER", $this->content_model, $def->content_model); - $this->child = false; - } - if (!empty($def->content_model_type)) { - $this->content_model_type = $def->content_model_type; - $this->child = false; - } - if (!is_null($def->child)) { - $this->child = $def->child; - } - if (!is_null($def->formatting)) { - $this->formatting = $def->formatting; - } - if ($def->descendants_are_inline) { - $this->descendants_are_inline = $def->descendants_are_inline; - } - } - - /** - * Merges one array into another, removes values which equal false - * @param $a1 Array by reference that is merged into - * @param $a2 Array that merges into $a1 - */ - private function _mergeAssocArray(&$a1, $a2) - { - foreach ($a2 as $k => $v) { - if ($v === false) { - if (isset($a1[$k])) { - unset($a1[$k]); - } - continue; - } - $a1[$k] = $v; - } - } -} - - - - - -/** - * A UTF-8 specific character encoder that handles cleaning and transforming. - * @note All functions in this class should be static. - */ -class HTMLPurifier_Encoder -{ - - /** - * Constructor throws fatal error if you attempt to instantiate class - */ - private function __construct() - { - trigger_error('Cannot instantiate encoder, call methods statically', E_USER_ERROR); - } - - /** - * Error-handler that mutes errors, alternative to shut-up operator. - */ - public static function muteErrorHandler() - { - } - - /** - * iconv wrapper which mutes errors, but doesn't work around bugs. - * @param string $in Input encoding - * @param string $out Output encoding - * @param string $text The text to convert - * @return string - */ - public static function unsafeIconv($in, $out, $text) - { - set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler')); - $r = iconv($in, $out, $text); - restore_error_handler(); - return $r; - } - - /** - * iconv wrapper which mutes errors and works around bugs. - * @param string $in Input encoding - * @param string $out Output encoding - * @param string $text The text to convert - * @param int $max_chunk_size - * @return string - */ - public static function iconv($in, $out, $text, $max_chunk_size = 8000) - { - $code = self::testIconvTruncateBug(); - if ($code == self::ICONV_OK) { - return self::unsafeIconv($in, $out, $text); - } elseif ($code == self::ICONV_TRUNCATES) { - // we can only work around this if the input character set - // is utf-8 - if ($in == 'utf-8') { - if ($max_chunk_size < 4) { - trigger_error('max_chunk_size is too small', E_USER_WARNING); - return false; - } - // split into 8000 byte chunks, but be careful to handle - // multibyte boundaries properly - if (($c = strlen($text)) <= $max_chunk_size) { - return self::unsafeIconv($in, $out, $text); - } - $r = ''; - $i = 0; - while (true) { - if ($i + $max_chunk_size >= $c) { - $r .= self::unsafeIconv($in, $out, substr($text, $i)); - break; - } - // wibble the boundary - if (0x80 != (0xC0 & ord($text[$i + $max_chunk_size]))) { - $chunk_size = $max_chunk_size; - } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 1]))) { - $chunk_size = $max_chunk_size - 1; - } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 2]))) { - $chunk_size = $max_chunk_size - 2; - } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 3]))) { - $chunk_size = $max_chunk_size - 3; - } else { - return false; // rather confusing UTF-8... - } - $chunk = substr($text, $i, $chunk_size); // substr doesn't mind overlong lengths - $r .= self::unsafeIconv($in, $out, $chunk); - $i += $chunk_size; - } - return $r; - } else { - return false; - } - } else { - return false; - } - } - - /** - * Cleans a UTF-8 string for well-formedness and SGML validity - * - * It will parse according to UTF-8 and return a valid UTF8 string, with - * non-SGML codepoints excluded. - * - * @param string $str The string to clean - * @param bool $force_php - * @return string - * - * @note Just for reference, the non-SGML code points are 0 to 31 and - * 127 to 159, inclusive. However, we allow code points 9, 10 - * and 13, which are the tab, line feed and carriage return - * respectively. 128 and above the code points map to multibyte - * UTF-8 representations. - * - * @note Fallback code adapted from utf8ToUnicode by Henri Sivonen and - * hsivonen@iki.fi at under the - * LGPL license. Notes on what changed are inside, but in general, - * the original code transformed UTF-8 text into an array of integer - * Unicode codepoints. Understandably, transforming that back to - * a string would be somewhat expensive, so the function was modded to - * directly operate on the string. However, this discourages code - * reuse, and the logic enumerated here would be useful for any - * function that needs to be able to understand UTF-8 characters. - * As of right now, only smart lossless character encoding converters - * would need that, and I'm probably not going to implement them. - * Once again, PHP 6 should solve all our problems. - */ - public static function cleanUTF8($str, $force_php = false) - { - // UTF-8 validity is checked since PHP 4.3.5 - // This is an optimization: if the string is already valid UTF-8, no - // need to do PHP stuff. 99% of the time, this will be the case. - // The regexp matches the XML char production, as well as well as excluding - // non-SGML codepoints U+007F to U+009F - if (preg_match( - '/^[\x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]*$/Du', - $str - )) { - return $str; - } - - $mState = 0; // cached expected number of octets after the current octet - // until the beginning of the next UTF8 character sequence - $mUcs4 = 0; // cached Unicode character - $mBytes = 1; // cached expected number of octets in the current sequence - - // original code involved an $out that was an array of Unicode - // codepoints. Instead of having to convert back into UTF-8, we've - // decided to directly append valid UTF-8 characters onto a string - // $out once they're done. $char accumulates raw bytes, while $mUcs4 - // turns into the Unicode code point, so there's some redundancy. - - $out = ''; - $char = ''; - - $len = strlen($str); - for ($i = 0; $i < $len; $i++) { - $in = ord($str{$i}); - $char .= $str[$i]; // append byte to char - if (0 == $mState) { - // When mState is zero we expect either a US-ASCII character - // or a multi-octet sequence. - if (0 == (0x80 & ($in))) { - // US-ASCII, pass straight through. - if (($in <= 31 || $in == 127) && - !($in == 9 || $in == 13 || $in == 10) // save \r\t\n - ) { - // control characters, remove - } else { - $out .= $char; - } - // reset - $char = ''; - $mBytes = 1; - } elseif (0xC0 == (0xE0 & ($in))) { - // First octet of 2 octet sequence - $mUcs4 = ($in); - $mUcs4 = ($mUcs4 & 0x1F) << 6; - $mState = 1; - $mBytes = 2; - } elseif (0xE0 == (0xF0 & ($in))) { - // First octet of 3 octet sequence - $mUcs4 = ($in); - $mUcs4 = ($mUcs4 & 0x0F) << 12; - $mState = 2; - $mBytes = 3; - } elseif (0xF0 == (0xF8 & ($in))) { - // First octet of 4 octet sequence - $mUcs4 = ($in); - $mUcs4 = ($mUcs4 & 0x07) << 18; - $mState = 3; - $mBytes = 4; - } elseif (0xF8 == (0xFC & ($in))) { - // First octet of 5 octet sequence. - // - // This is illegal because the encoded codepoint must be - // either: - // (a) not the shortest form or - // (b) outside the Unicode range of 0-0x10FFFF. - // Rather than trying to resynchronize, we will carry on - // until the end of the sequence and let the later error - // handling code catch it. - $mUcs4 = ($in); - $mUcs4 = ($mUcs4 & 0x03) << 24; - $mState = 4; - $mBytes = 5; - } elseif (0xFC == (0xFE & ($in))) { - // First octet of 6 octet sequence, see comments for 5 - // octet sequence. - $mUcs4 = ($in); - $mUcs4 = ($mUcs4 & 1) << 30; - $mState = 5; - $mBytes = 6; - } else { - // Current octet is neither in the US-ASCII range nor a - // legal first octet of a multi-octet sequence. - $mState = 0; - $mUcs4 = 0; - $mBytes = 1; - $char = ''; - } - } else { - // When mState is non-zero, we expect a continuation of the - // multi-octet sequence - if (0x80 == (0xC0 & ($in))) { - // Legal continuation. - $shift = ($mState - 1) * 6; - $tmp = $in; - $tmp = ($tmp & 0x0000003F) << $shift; - $mUcs4 |= $tmp; - - if (0 == --$mState) { - // End of the multi-octet sequence. mUcs4 now contains - // the final Unicode codepoint to be output - - // Check for illegal sequences and codepoints. - - // From Unicode 3.1, non-shortest form is illegal - if (((2 == $mBytes) && ($mUcs4 < 0x0080)) || - ((3 == $mBytes) && ($mUcs4 < 0x0800)) || - ((4 == $mBytes) && ($mUcs4 < 0x10000)) || - (4 < $mBytes) || - // From Unicode 3.2, surrogate characters = illegal - (($mUcs4 & 0xFFFFF800) == 0xD800) || - // Codepoints outside the Unicode range are illegal - ($mUcs4 > 0x10FFFF) - ) { - - } elseif (0xFEFF != $mUcs4 && // omit BOM - // check for valid Char unicode codepoints - ( - 0x9 == $mUcs4 || - 0xA == $mUcs4 || - 0xD == $mUcs4 || - (0x20 <= $mUcs4 && 0x7E >= $mUcs4) || - // 7F-9F is not strictly prohibited by XML, - // but it is non-SGML, and thus we don't allow it - (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) || - (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4) - ) - ) { - $out .= $char; - } - // initialize UTF8 cache (reset) - $mState = 0; - $mUcs4 = 0; - $mBytes = 1; - $char = ''; - } - } else { - // ((0xC0 & (*in) != 0x80) && (mState != 0)) - // Incomplete multi-octet sequence. - // used to result in complete fail, but we'll reset - $mState = 0; - $mUcs4 = 0; - $mBytes = 1; - $char =''; - } - } - } - return $out; - } - - /** - * Translates a Unicode codepoint into its corresponding UTF-8 character. - * @note Based on Feyd's function at - * , - * which is in public domain. - * @note While we're going to do code point parsing anyway, a good - * optimization would be to refuse to translate code points that - * are non-SGML characters. However, this could lead to duplication. - * @note This is very similar to the unichr function in - * maintenance/generate-entity-file.php (although this is superior, - * due to its sanity checks). - */ - - // +----------+----------+----------+----------+ - // | 33222222 | 22221111 | 111111 | | - // | 10987654 | 32109876 | 54321098 | 76543210 | bit - // +----------+----------+----------+----------+ - // | | | | 0xxxxxxx | 1 byte 0x00000000..0x0000007F - // | | | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF - // | | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF - // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF - // +----------+----------+----------+----------+ - // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF) - // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes - // +----------+----------+----------+----------+ - - public static function unichr($code) - { - if ($code > 1114111 or $code < 0 or - ($code >= 55296 and $code <= 57343)) { - // bits are set outside the "valid" range as defined - // by UNICODE 4.1.0 - return ''; - } - - $x = $y = $z = $w = 0; - if ($code < 128) { - // regular ASCII character - $x = $code; - } else { - // set up bits for UTF-8 - $x = ($code & 63) | 128; - if ($code < 2048) { - $y = (($code & 2047) >> 6) | 192; - } else { - $y = (($code & 4032) >> 6) | 128; - if ($code < 65536) { - $z = (($code >> 12) & 15) | 224; - } else { - $z = (($code >> 12) & 63) | 128; - $w = (($code >> 18) & 7) | 240; - } - } - } - // set up the actual character - $ret = ''; - if ($w) { - $ret .= chr($w); - } - if ($z) { - $ret .= chr($z); - } - if ($y) { - $ret .= chr($y); - } - $ret .= chr($x); - - return $ret; - } - - /** - * @return bool - */ - public static function iconvAvailable() - { - static $iconv = null; - if ($iconv === null) { - $iconv = function_exists('iconv') && self::testIconvTruncateBug() != self::ICONV_UNUSABLE; - } - return $iconv; - } - - /** - * Convert a string to UTF-8 based on configuration. - * @param string $str The string to convert - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return string - */ - public static function convertToUTF8($str, $config, $context) - { - $encoding = $config->get('Core.Encoding'); - if ($encoding === 'utf-8') { - return $str; - } - static $iconv = null; - if ($iconv === null) { - $iconv = self::iconvAvailable(); - } - if ($iconv && !$config->get('Test.ForceNoIconv')) { - // unaffected by bugs, since UTF-8 support all characters - $str = self::unsafeIconv($encoding, 'utf-8//IGNORE', $str); - if ($str === false) { - // $encoding is not a valid encoding - trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR); - return ''; - } - // If the string is bjorked by Shift_JIS or a similar encoding - // that doesn't support all of ASCII, convert the naughty - // characters to their true byte-wise ASCII/UTF-8 equivalents. - $str = strtr($str, self::testEncodingSupportsASCII($encoding)); - return $str; - } elseif ($encoding === 'iso-8859-1') { - $str = utf8_encode($str); - return $str; - } - $bug = HTMLPurifier_Encoder::testIconvTruncateBug(); - if ($bug == self::ICONV_OK) { - trigger_error('Encoding not supported, please install iconv', E_USER_ERROR); - } else { - trigger_error( - 'You have a buggy version of iconv, see https://bugs.php.net/bug.php?id=48147 ' . - 'and http://sourceware.org/bugzilla/show_bug.cgi?id=13541', - E_USER_ERROR - ); - } - } - - /** - * Converts a string from UTF-8 based on configuration. - * @param string $str The string to convert - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return string - * @note Currently, this is a lossy conversion, with unexpressable - * characters being omitted. - */ - public static function convertFromUTF8($str, $config, $context) - { - $encoding = $config->get('Core.Encoding'); - if ($escape = $config->get('Core.EscapeNonASCIICharacters')) { - $str = self::convertToASCIIDumbLossless($str); - } - if ($encoding === 'utf-8') { - return $str; - } - static $iconv = null; - if ($iconv === null) { - $iconv = self::iconvAvailable(); - } - if ($iconv && !$config->get('Test.ForceNoIconv')) { - // Undo our previous fix in convertToUTF8, otherwise iconv will barf - $ascii_fix = self::testEncodingSupportsASCII($encoding); - if (!$escape && !empty($ascii_fix)) { - $clear_fix = array(); - foreach ($ascii_fix as $utf8 => $native) { - $clear_fix[$utf8] = ''; - } - $str = strtr($str, $clear_fix); - } - $str = strtr($str, array_flip($ascii_fix)); - // Normal stuff - $str = self::iconv('utf-8', $encoding . '//IGNORE', $str); - return $str; - } elseif ($encoding === 'iso-8859-1') { - $str = utf8_decode($str); - return $str; - } - trigger_error('Encoding not supported', E_USER_ERROR); - // You might be tempted to assume that the ASCII representation - // might be OK, however, this is *not* universally true over all - // encodings. So we take the conservative route here, rather - // than forcibly turn on %Core.EscapeNonASCIICharacters - } - - /** - * Lossless (character-wise) conversion of HTML to ASCII - * @param string $str UTF-8 string to be converted to ASCII - * @return string ASCII encoded string with non-ASCII character entity-ized - * @warning Adapted from MediaWiki, claiming fair use: this is a common - * algorithm. If you disagree with this license fudgery, - * implement it yourself. - * @note Uses decimal numeric entities since they are best supported. - * @note This is a DUMB function: it has no concept of keeping - * character entities that the projected character encoding - * can allow. We could possibly implement a smart version - * but that would require it to also know which Unicode - * codepoints the charset supported (not an easy task). - * @note Sort of with cleanUTF8() but it assumes that $str is - * well-formed UTF-8 - */ - public static function convertToASCIIDumbLossless($str) - { - $bytesleft = 0; - $result = ''; - $working = 0; - $len = strlen($str); - for ($i = 0; $i < $len; $i++) { - $bytevalue = ord($str[$i]); - if ($bytevalue <= 0x7F) { //0xxx xxxx - $result .= chr($bytevalue); - $bytesleft = 0; - } elseif ($bytevalue <= 0xBF) { //10xx xxxx - $working = $working << 6; - $working += ($bytevalue & 0x3F); - $bytesleft--; - if ($bytesleft <= 0) { - $result .= "&#" . $working . ";"; - } - } elseif ($bytevalue <= 0xDF) { //110x xxxx - $working = $bytevalue & 0x1F; - $bytesleft = 1; - } elseif ($bytevalue <= 0xEF) { //1110 xxxx - $working = $bytevalue & 0x0F; - $bytesleft = 2; - } else { //1111 0xxx - $working = $bytevalue & 0x07; - $bytesleft = 3; - } - } - return $result; - } - - /** No bugs detected in iconv. */ - const ICONV_OK = 0; - - /** Iconv truncates output if converting from UTF-8 to another - * character set with //IGNORE, and a non-encodable character is found */ - const ICONV_TRUNCATES = 1; - - /** Iconv does not support //IGNORE, making it unusable for - * transcoding purposes */ - const ICONV_UNUSABLE = 2; - - /** - * glibc iconv has a known bug where it doesn't handle the magic - * //IGNORE stanza correctly. In particular, rather than ignore - * characters, it will return an EILSEQ after consuming some number - * of characters, and expect you to restart iconv as if it were - * an E2BIG. Old versions of PHP did not respect the errno, and - * returned the fragment, so as a result you would see iconv - * mysteriously truncating output. We can work around this by - * manually chopping our input into segments of about 8000 - * characters, as long as PHP ignores the error code. If PHP starts - * paying attention to the error code, iconv becomes unusable. - * - * @return int Error code indicating severity of bug. - */ - public static function testIconvTruncateBug() - { - static $code = null; - if ($code === null) { - // better not use iconv, otherwise infinite loop! - $r = self::unsafeIconv('utf-8', 'ascii//IGNORE', "\xCE\xB1" . str_repeat('a', 9000)); - if ($r === false) { - $code = self::ICONV_UNUSABLE; - } elseif (($c = strlen($r)) < 9000) { - $code = self::ICONV_TRUNCATES; - } elseif ($c > 9000) { - trigger_error( - 'Your copy of iconv is extremely buggy. Please notify HTML Purifier maintainers: ' . - 'include your iconv version as per phpversion()', - E_USER_ERROR - ); - } else { - $code = self::ICONV_OK; - } - } - return $code; - } - - /** - * This expensive function tests whether or not a given character - * encoding supports ASCII. 7/8-bit encodings like Shift_JIS will - * fail this test, and require special processing. Variable width - * encodings shouldn't ever fail. - * - * @param string $encoding Encoding name to test, as per iconv format - * @param bool $bypass Whether or not to bypass the precompiled arrays. - * @return Array of UTF-8 characters to their corresponding ASCII, - * which can be used to "undo" any overzealous iconv action. - */ - public static function testEncodingSupportsASCII($encoding, $bypass = false) - { - // All calls to iconv here are unsafe, proof by case analysis: - // If ICONV_OK, no difference. - // If ICONV_TRUNCATE, all calls involve one character inputs, - // so bug is not triggered. - // If ICONV_UNUSABLE, this call is irrelevant - static $encodings = array(); - if (!$bypass) { - if (isset($encodings[$encoding])) { - return $encodings[$encoding]; - } - $lenc = strtolower($encoding); - switch ($lenc) { - case 'shift_jis': - return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~'); - case 'johab': - return array("\xE2\x82\xA9" => '\\'); - } - if (strpos($lenc, 'iso-8859-') === 0) { - return array(); - } - } - $ret = array(); - if (self::unsafeIconv('UTF-8', $encoding, 'a') === false) { - return false; - } - for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars - $c = chr($i); // UTF-8 char - $r = self::unsafeIconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion - if ($r === '' || - // This line is needed for iconv implementations that do not - // omit characters that do not exist in the target character set - ($r === $c && self::unsafeIconv($encoding, 'UTF-8//IGNORE', $r) !== $c) - ) { - // Reverse engineer: what's the UTF-8 equiv of this byte - // sequence? This assumes that there's no variable width - // encoding that doesn't support ASCII. - $ret[self::unsafeIconv($encoding, 'UTF-8//IGNORE', $c)] = $c; - } - } - $encodings[$encoding] = $ret; - return $ret; - } -} - - - - - -/** - * Object that provides entity lookup table from entity name to character - */ -class HTMLPurifier_EntityLookup -{ - /** - * Assoc array of entity name to character represented. - * @type array - */ - public $table; - - /** - * Sets up the entity lookup table from the serialized file contents. - * @param bool $file - * @note The serialized contents are versioned, but were generated - * using the maintenance script generate_entity_file.php - * @warning This is not in constructor to help enforce the Singleton - */ - public function setup($file = false) - { - if (!$file) { - $file = HTMLPURIFIER_PREFIX . '/HTMLPurifier/EntityLookup/entities.ser'; - } - $this->table = unserialize(file_get_contents($file)); - } - - /** - * Retrieves sole instance of the object. - * @param bool|HTMLPurifier_EntityLookup $prototype Optional prototype of custom lookup table to overload with. - * @return HTMLPurifier_EntityLookup - */ - public static function instance($prototype = false) - { - // no references, since PHP doesn't copy unless modified - static $instance = null; - if ($prototype) { - $instance = $prototype; - } elseif (!$instance) { - $instance = new HTMLPurifier_EntityLookup(); - $instance->setup(); - } - return $instance; - } -} - - - - - -// if want to implement error collecting here, we'll need to use some sort -// of global data (probably trigger_error) because it's impossible to pass -// $config or $context to the callback functions. - -/** - * Handles referencing and derefencing character entities - */ -class HTMLPurifier_EntityParser -{ - - /** - * Reference to entity lookup table. - * @type HTMLPurifier_EntityLookup - */ - protected $_entity_lookup; - - /** - * Callback regex string for parsing entities. - * @type string - */ - protected $_substituteEntitiesRegex = - '/&(?:[#]x([a-fA-F0-9]+)|[#]0*(\d+)|([A-Za-z_:][A-Za-z0-9.\-_:]*));?/'; - // 1. hex 2. dec 3. string (XML style) - - /** - * Decimal to parsed string conversion table for special entities. - * @type array - */ - protected $_special_dec2str = - array( - 34 => '"', - 38 => '&', - 39 => "'", - 60 => '<', - 62 => '>' - ); - - /** - * Stripped entity names to decimal conversion table for special entities. - * @type array - */ - protected $_special_ent2dec = - array( - 'quot' => 34, - 'amp' => 38, - 'lt' => 60, - 'gt' => 62 - ); - - /** - * Substitutes non-special entities with their parsed equivalents. Since - * running this whenever you have parsed character is t3h 5uck, we run - * it before everything else. - * - * @param string $string String to have non-special entities parsed. - * @return string Parsed string. - */ - public function substituteNonSpecialEntities($string) - { - // it will try to detect missing semicolons, but don't rely on it - return preg_replace_callback( - $this->_substituteEntitiesRegex, - array($this, 'nonSpecialEntityCallback'), - $string - ); - } - - /** - * Callback function for substituteNonSpecialEntities() that does the work. - * - * @param array $matches PCRE matches array, with 0 the entire match, and - * either index 1, 2 or 3 set with a hex value, dec value, - * or string (respectively). - * @return string Replacement string. - */ - - protected function nonSpecialEntityCallback($matches) - { - // replaces all but big five - $entity = $matches[0]; - $is_num = (@$matches[0][1] === '#'); - if ($is_num) { - $is_hex = (@$entity[2] === 'x'); - $code = $is_hex ? hexdec($matches[1]) : (int) $matches[2]; - // abort for special characters - if (isset($this->_special_dec2str[$code])) { - return $entity; - } - return HTMLPurifier_Encoder::unichr($code); - } else { - if (isset($this->_special_ent2dec[$matches[3]])) { - return $entity; - } - if (!$this->_entity_lookup) { - $this->_entity_lookup = HTMLPurifier_EntityLookup::instance(); - } - if (isset($this->_entity_lookup->table[$matches[3]])) { - return $this->_entity_lookup->table[$matches[3]]; - } else { - return $entity; - } - } - } - - /** - * Substitutes only special entities with their parsed equivalents. - * - * @notice We try to avoid calling this function because otherwise, it - * would have to be called a lot (for every parsed section). - * - * @param string $string String to have non-special entities parsed. - * @return string Parsed string. - */ - public function substituteSpecialEntities($string) - { - return preg_replace_callback( - $this->_substituteEntitiesRegex, - array($this, 'specialEntityCallback'), - $string - ); - } - - /** - * Callback function for substituteSpecialEntities() that does the work. - * - * This callback has same syntax as nonSpecialEntityCallback(). - * - * @param array $matches PCRE-style matches array, with 0 the entire match, and - * either index 1, 2 or 3 set with a hex value, dec value, - * or string (respectively). - * @return string Replacement string. - */ - protected function specialEntityCallback($matches) - { - $entity = $matches[0]; - $is_num = (@$matches[0][1] === '#'); - if ($is_num) { - $is_hex = (@$entity[2] === 'x'); - $int = $is_hex ? hexdec($matches[1]) : (int) $matches[2]; - return isset($this->_special_dec2str[$int]) ? - $this->_special_dec2str[$int] : - $entity; - } else { - return isset($this->_special_ent2dec[$matches[3]]) ? - $this->_special_ent2dec[$matches[3]] : - $entity; - } - } -} - - - - - -/** - * Error collection class that enables HTML Purifier to report HTML - * problems back to the user - */ -class HTMLPurifier_ErrorCollector -{ - - /** - * Identifiers for the returned error array. These are purposely numeric - * so list() can be used. - */ - const LINENO = 0; - const SEVERITY = 1; - const MESSAGE = 2; - const CHILDREN = 3; - - /** - * @type array - */ - protected $errors; - - /** - * @type array - */ - protected $_current; - - /** - * @type array - */ - protected $_stacks = array(array()); - - /** - * @type HTMLPurifier_Language - */ - protected $locale; - - /** - * @type HTMLPurifier_Generator - */ - protected $generator; - - /** - * @type HTMLPurifier_Context - */ - protected $context; - - /** - * @type array - */ - protected $lines = array(); - - /** - * @param HTMLPurifier_Context $context - */ - public function __construct($context) - { - $this->locale =& $context->get('Locale'); - $this->context = $context; - $this->_current =& $this->_stacks[0]; - $this->errors =& $this->_stacks[0]; - } - - /** - * Sends an error message to the collector for later use - * @param int $severity Error severity, PHP error style (don't use E_USER_) - * @param string $msg Error message text - */ - public function send($severity, $msg) - { - $args = array(); - if (func_num_args() > 2) { - $args = func_get_args(); - array_shift($args); - unset($args[0]); - } - - $token = $this->context->get('CurrentToken', true); - $line = $token ? $token->line : $this->context->get('CurrentLine', true); - $col = $token ? $token->col : $this->context->get('CurrentCol', true); - $attr = $this->context->get('CurrentAttr', true); - - // perform special substitutions, also add custom parameters - $subst = array(); - if (!is_null($token)) { - $args['CurrentToken'] = $token; - } - if (!is_null($attr)) { - $subst['$CurrentAttr.Name'] = $attr; - if (isset($token->attr[$attr])) { - $subst['$CurrentAttr.Value'] = $token->attr[$attr]; - } - } - - if (empty($args)) { - $msg = $this->locale->getMessage($msg); - } else { - $msg = $this->locale->formatMessage($msg, $args); - } - - if (!empty($subst)) { - $msg = strtr($msg, $subst); - } - - // (numerically indexed) - $error = array( - self::LINENO => $line, - self::SEVERITY => $severity, - self::MESSAGE => $msg, - self::CHILDREN => array() - ); - $this->_current[] = $error; - - // NEW CODE BELOW ... - // Top-level errors are either: - // TOKEN type, if $value is set appropriately, or - // "syntax" type, if $value is null - $new_struct = new HTMLPurifier_ErrorStruct(); - $new_struct->type = HTMLPurifier_ErrorStruct::TOKEN; - if ($token) { - $new_struct->value = clone $token; - } - if (is_int($line) && is_int($col)) { - if (isset($this->lines[$line][$col])) { - $struct = $this->lines[$line][$col]; - } else { - $struct = $this->lines[$line][$col] = $new_struct; - } - // These ksorts may present a performance problem - ksort($this->lines[$line], SORT_NUMERIC); - } else { - if (isset($this->lines[-1])) { - $struct = $this->lines[-1]; - } else { - $struct = $this->lines[-1] = $new_struct; - } - } - ksort($this->lines, SORT_NUMERIC); - - // Now, check if we need to operate on a lower structure - if (!empty($attr)) { - $struct = $struct->getChild(HTMLPurifier_ErrorStruct::ATTR, $attr); - if (!$struct->value) { - $struct->value = array($attr, 'PUT VALUE HERE'); - } - } - if (!empty($cssprop)) { - $struct = $struct->getChild(HTMLPurifier_ErrorStruct::CSSPROP, $cssprop); - if (!$struct->value) { - // if we tokenize CSS this might be a little more difficult to do - $struct->value = array($cssprop, 'PUT VALUE HERE'); - } - } - - // Ok, structs are all setup, now time to register the error - $struct->addError($severity, $msg); - } - - /** - * Retrieves raw error data for custom formatter to use - */ - public function getRaw() - { - return $this->errors; - } - - /** - * Default HTML formatting implementation for error messages - * @param HTMLPurifier_Config $config Configuration, vital for HTML output nature - * @param array $errors Errors array to display; used for recursion. - * @return string - */ - public function getHTMLFormatted($config, $errors = null) - { - $ret = array(); - - $this->generator = new HTMLPurifier_Generator($config, $this->context); - if ($errors === null) { - $errors = $this->errors; - } - - // 'At line' message needs to be removed - - // generation code for new structure goes here. It needs to be recursive. - foreach ($this->lines as $line => $col_array) { - if ($line == -1) { - continue; - } - foreach ($col_array as $col => $struct) { - $this->_renderStruct($ret, $struct, $line, $col); - } - } - if (isset($this->lines[-1])) { - $this->_renderStruct($ret, $this->lines[-1]); - } - - if (empty($errors)) { - return '

' . $this->locale->getMessage('ErrorCollector: No errors') . '

'; - } else { - return '
  • ' . implode('
  • ', $ret) . '
'; - } - - } - - private function _renderStruct(&$ret, $struct, $line = null, $col = null) - { - $stack = array($struct); - $context_stack = array(array()); - while ($current = array_pop($stack)) { - $context = array_pop($context_stack); - foreach ($current->errors as $error) { - list($severity, $msg) = $error; - $string = ''; - $string .= '
'; - // W3C uses an icon to indicate the severity of the error. - $error = $this->locale->getErrorName($severity); - $string .= "$error "; - if (!is_null($line) && !is_null($col)) { - $string .= "Line $line, Column $col: "; - } else { - $string .= 'End of Document: '; - } - $string .= '' . $this->generator->escape($msg) . ' '; - $string .= '
'; - // Here, have a marker for the character on the column appropriate. - // Be sure to clip extremely long lines. - //$string .= '
';
-                //$string .= '';
-                //$string .= '
'; - $ret[] = $string; - } - foreach ($current->children as $array) { - $context[] = $current; - $stack = array_merge($stack, array_reverse($array, true)); - for ($i = count($array); $i > 0; $i--) { - $context_stack[] = $context; - } - } - } - } -} - - - - - -/** - * Records errors for particular segments of an HTML document such as tokens, - * attributes or CSS properties. They can contain error structs (which apply - * to components of what they represent), but their main purpose is to hold - * errors applying to whatever struct is being used. - */ -class HTMLPurifier_ErrorStruct -{ - - /** - * Possible values for $children first-key. Note that top-level structures - * are automatically token-level. - */ - const TOKEN = 0; - const ATTR = 1; - const CSSPROP = 2; - - /** - * Type of this struct. - * @type string - */ - public $type; - - /** - * Value of the struct we are recording errors for. There are various - * values for this: - * - TOKEN: Instance of HTMLPurifier_Token - * - ATTR: array('attr-name', 'value') - * - CSSPROP: array('prop-name', 'value') - * @type mixed - */ - public $value; - - /** - * Errors registered for this structure. - * @type array - */ - public $errors = array(); - - /** - * Child ErrorStructs that are from this structure. For example, a TOKEN - * ErrorStruct would contain ATTR ErrorStructs. This is a multi-dimensional - * array in structure: [TYPE]['identifier'] - * @type array - */ - public $children = array(); - - /** - * @param string $type - * @param string $id - * @return mixed - */ - public function getChild($type, $id) - { - if (!isset($this->children[$type][$id])) { - $this->children[$type][$id] = new HTMLPurifier_ErrorStruct(); - $this->children[$type][$id]->type = $type; - } - return $this->children[$type][$id]; - } - - /** - * @param int $severity - * @param string $message - */ - public function addError($severity, $message) - { - $this->errors[] = array($severity, $message); - } -} - - - - - -/** - * Global exception class for HTML Purifier; any exceptions we throw - * are from here. - */ -class HTMLPurifier_Exception extends Exception -{ - -} - - - - - -/** - * Represents a pre or post processing filter on HTML Purifier's output - * - * Sometimes, a little ad-hoc fixing of HTML has to be done before - * it gets sent through HTML Purifier: you can use filters to acheive - * this effect. For instance, YouTube videos can be preserved using - * this manner. You could have used a decorator for this task, but - * PHP's support for them is not terribly robust, so we're going - * to just loop through the filters. - * - * Filters should be exited first in, last out. If there are three filters, - * named 1, 2 and 3, the order of execution should go 1->preFilter, - * 2->preFilter, 3->preFilter, purify, 3->postFilter, 2->postFilter, - * 1->postFilter. - * - * @note Methods are not declared abstract as it is perfectly legitimate - * for an implementation not to want anything to happen on a step - */ - -class HTMLPurifier_Filter -{ - - /** - * Name of the filter for identification purposes. - * @type string - */ - public $name; - - /** - * Pre-processor function, handles HTML before HTML Purifier - * @param string $html - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return string - */ - public function preFilter($html, $config, $context) - { - return $html; - } - - /** - * Post-processor function, handles HTML after HTML Purifier - * @param string $html - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return string - */ - public function postFilter($html, $config, $context) - { - return $html; - } -} - - - - - -/** - * Generates HTML from tokens. - * @todo Refactor interface so that configuration/context is determined - * upon instantiation, no need for messy generateFromTokens() calls - * @todo Make some of the more internal functions protected, and have - * unit tests work around that - */ -class HTMLPurifier_Generator -{ - - /** - * Whether or not generator should produce XML output. - * @type bool - */ - private $_xhtml = true; - - /** - * :HACK: Whether or not generator should comment the insides of )#si', - array($this, 'scriptCallback'), - $html - ); - } - - $html = $this->normalize($html, $config, $context); - - $cursor = 0; // our location in the text - $inside_tag = false; // whether or not we're parsing the inside of a tag - $array = array(); // result array - - // This is also treated to mean maintain *column* numbers too - $maintain_line_numbers = $config->get('Core.MaintainLineNumbers'); - - if ($maintain_line_numbers === null) { - // automatically determine line numbering by checking - // if error collection is on - $maintain_line_numbers = $config->get('Core.CollectErrors'); - } - - if ($maintain_line_numbers) { - $current_line = 1; - $current_col = 0; - $length = strlen($html); - } else { - $current_line = false; - $current_col = false; - $length = false; - } - $context->register('CurrentLine', $current_line); - $context->register('CurrentCol', $current_col); - $nl = "\n"; - // how often to manually recalculate. This will ALWAYS be right, - // but it's pretty wasteful. Set to 0 to turn off - $synchronize_interval = $config->get('Core.DirectLexLineNumberSyncInterval'); - - $e = false; - if ($config->get('Core.CollectErrors')) { - $e =& $context->get('ErrorCollector'); - } - - // for testing synchronization - $loops = 0; - - while (++$loops) { - // $cursor is either at the start of a token, or inside of - // a tag (i.e. there was a < immediately before it), as indicated - // by $inside_tag - - if ($maintain_line_numbers) { - // $rcursor, however, is always at the start of a token. - $rcursor = $cursor - (int)$inside_tag; - - // Column number is cheap, so we calculate it every round. - // We're interested at the *end* of the newline string, so - // we need to add strlen($nl) == 1 to $nl_pos before subtracting it - // from our "rcursor" position. - $nl_pos = strrpos($html, $nl, $rcursor - $length); - $current_col = $rcursor - (is_bool($nl_pos) ? 0 : $nl_pos + 1); - - // recalculate lines - if ($synchronize_interval && // synchronization is on - $cursor > 0 && // cursor is further than zero - $loops % $synchronize_interval === 0) { // time to synchronize! - $current_line = 1 + $this->substrCount($html, $nl, 0, $cursor); - } - } - - $position_next_lt = strpos($html, '<', $cursor); - $position_next_gt = strpos($html, '>', $cursor); - - // triggers on "asdf" but not "asdf " - // special case to set up context - if ($position_next_lt === $cursor) { - $inside_tag = true; - $cursor++; - } - - if (!$inside_tag && $position_next_lt !== false) { - // We are not inside tag and there still is another tag to parse - $token = new - HTMLPurifier_Token_Text( - $this->parseData( - substr( - $html, - $cursor, - $position_next_lt - $cursor - ) - ) - ); - if ($maintain_line_numbers) { - $token->rawPosition($current_line, $current_col); - $current_line += $this->substrCount($html, $nl, $cursor, $position_next_lt - $cursor); - } - $array[] = $token; - $cursor = $position_next_lt + 1; - $inside_tag = true; - continue; - } elseif (!$inside_tag) { - // We are not inside tag but there are no more tags - // If we're already at the end, break - if ($cursor === strlen($html)) { - break; - } - // Create Text of rest of string - $token = new - HTMLPurifier_Token_Text( - $this->parseData( - substr( - $html, - $cursor - ) - ) - ); - if ($maintain_line_numbers) { - $token->rawPosition($current_line, $current_col); - } - $array[] = $token; - break; - } elseif ($inside_tag && $position_next_gt !== false) { - // We are in tag and it is well formed - // Grab the internals of the tag - $strlen_segment = $position_next_gt - $cursor; - - if ($strlen_segment < 1) { - // there's nothing to process! - $token = new HTMLPurifier_Token_Text('<'); - $cursor++; - continue; - } - - $segment = substr($html, $cursor, $strlen_segment); - - if ($segment === false) { - // somehow, we attempted to access beyond the end of - // the string, defense-in-depth, reported by Nate Abele - break; - } - - // Check if it's a comment - if (substr($segment, 0, 3) === '!--') { - // re-determine segment length, looking for --> - $position_comment_end = strpos($html, '-->', $cursor); - if ($position_comment_end === false) { - // uh oh, we have a comment that extends to - // infinity. Can't be helped: set comment - // end position to end of string - if ($e) { - $e->send(E_WARNING, 'Lexer: Unclosed comment'); - } - $position_comment_end = strlen($html); - $end = true; - } else { - $end = false; - } - $strlen_segment = $position_comment_end - $cursor; - $segment = substr($html, $cursor, $strlen_segment); - $token = new - HTMLPurifier_Token_Comment( - substr( - $segment, - 3, - $strlen_segment - 3 - ) - ); - if ($maintain_line_numbers) { - $token->rawPosition($current_line, $current_col); - $current_line += $this->substrCount($html, $nl, $cursor, $strlen_segment); - } - $array[] = $token; - $cursor = $end ? $position_comment_end : $position_comment_end + 3; - $inside_tag = false; - continue; - } - - // Check if it's an end tag - $is_end_tag = (strpos($segment, '/') === 0); - if ($is_end_tag) { - $type = substr($segment, 1); - $token = new HTMLPurifier_Token_End($type); - if ($maintain_line_numbers) { - $token->rawPosition($current_line, $current_col); - $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); - } - $array[] = $token; - $inside_tag = false; - $cursor = $position_next_gt + 1; - continue; - } - - // Check leading character is alnum, if not, we may - // have accidently grabbed an emoticon. Translate into - // text and go our merry way - if (!ctype_alpha($segment[0])) { - // XML: $segment[0] !== '_' && $segment[0] !== ':' - if ($e) { - $e->send(E_NOTICE, 'Lexer: Unescaped lt'); - } - $token = new HTMLPurifier_Token_Text('<'); - if ($maintain_line_numbers) { - $token->rawPosition($current_line, $current_col); - $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); - } - $array[] = $token; - $inside_tag = false; - continue; - } - - // Check if it is explicitly self closing, if so, remove - // trailing slash. Remember, we could have a tag like
, so - // any later token processing scripts must convert improperly - // classified EmptyTags from StartTags. - $is_self_closing = (strrpos($segment, '/') === $strlen_segment - 1); - if ($is_self_closing) { - $strlen_segment--; - $segment = substr($segment, 0, $strlen_segment); - } - - // Check if there are any attributes - $position_first_space = strcspn($segment, $this->_whitespace); - - if ($position_first_space >= $strlen_segment) { - if ($is_self_closing) { - $token = new HTMLPurifier_Token_Empty($segment); - } else { - $token = new HTMLPurifier_Token_Start($segment); - } - if ($maintain_line_numbers) { - $token->rawPosition($current_line, $current_col); - $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); - } - $array[] = $token; - $inside_tag = false; - $cursor = $position_next_gt + 1; - continue; - } - - // Grab out all the data - $type = substr($segment, 0, $position_first_space); - $attribute_string = - trim( - substr( - $segment, - $position_first_space - ) - ); - if ($attribute_string) { - $attr = $this->parseAttributeString( - $attribute_string, - $config, - $context - ); - } else { - $attr = array(); - } - - if ($is_self_closing) { - $token = new HTMLPurifier_Token_Empty($type, $attr); - } else { - $token = new HTMLPurifier_Token_Start($type, $attr); - } - if ($maintain_line_numbers) { - $token->rawPosition($current_line, $current_col); - $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); - } - $array[] = $token; - $cursor = $position_next_gt + 1; - $inside_tag = false; - continue; - } else { - // inside tag, but there's no ending > sign - if ($e) { - $e->send(E_WARNING, 'Lexer: Missing gt'); - } - $token = new - HTMLPurifier_Token_Text( - '<' . - $this->parseData( - substr($html, $cursor) - ) - ); - if ($maintain_line_numbers) { - $token->rawPosition($current_line, $current_col); - } - // no cursor scroll? Hmm... - $array[] = $token; - break; - } - break; - } - - $context->destroy('CurrentLine'); - $context->destroy('CurrentCol'); - return $array; - } - - /** - * PHP 5.0.x compatible substr_count that implements offset and length - * @param string $haystack - * @param string $needle - * @param int $offset - * @param int $length - * @return int - */ - protected function substrCount($haystack, $needle, $offset, $length) - { - static $oldVersion; - if ($oldVersion === null) { - $oldVersion = version_compare(PHP_VERSION, '5.1', '<'); - } - if ($oldVersion) { - $haystack = substr($haystack, $offset, $length); - return substr_count($haystack, $needle); - } else { - return substr_count($haystack, $needle, $offset, $length); - } - } - - /** - * Takes the inside of an HTML tag and makes an assoc array of attributes. - * - * @param string $string Inside of tag excluding name. - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return array Assoc array of attributes. - */ - public function parseAttributeString($string, $config, $context) - { - $string = (string)$string; // quick typecast - - if ($string == '') { - return array(); - } // no attributes - - $e = false; - if ($config->get('Core.CollectErrors')) { - $e =& $context->get('ErrorCollector'); - } - - // let's see if we can abort as quickly as possible - // one equal sign, no spaces => one attribute - $num_equal = substr_count($string, '='); - $has_space = strpos($string, ' '); - if ($num_equal === 0 && !$has_space) { - // bool attribute - return array($string => $string); - } elseif ($num_equal === 1 && !$has_space) { - // only one attribute - list($key, $quoted_value) = explode('=', $string); - $quoted_value = trim($quoted_value); - if (!$key) { - if ($e) { - $e->send(E_ERROR, 'Lexer: Missing attribute key'); - } - return array(); - } - if (!$quoted_value) { - return array($key => ''); - } - $first_char = @$quoted_value[0]; - $last_char = @$quoted_value[strlen($quoted_value) - 1]; - - $same_quote = ($first_char == $last_char); - $open_quote = ($first_char == '"' || $first_char == "'"); - - if ($same_quote && $open_quote) { - // well behaved - $value = substr($quoted_value, 1, strlen($quoted_value) - 2); - } else { - // not well behaved - if ($open_quote) { - if ($e) { - $e->send(E_ERROR, 'Lexer: Missing end quote'); - } - $value = substr($quoted_value, 1); - } else { - $value = $quoted_value; - } - } - if ($value === false) { - $value = ''; - } - return array($key => $this->parseData($value)); - } - - // setup loop environment - $array = array(); // return assoc array of attributes - $cursor = 0; // current position in string (moves forward) - $size = strlen($string); // size of the string (stays the same) - - // if we have unquoted attributes, the parser expects a terminating - // space, so let's guarantee that there's always a terminating space. - $string .= ' '; - - $old_cursor = -1; - while ($cursor < $size) { - if ($old_cursor >= $cursor) { - throw new Exception("Infinite loop detected"); - } - $old_cursor = $cursor; - - $cursor += ($value = strspn($string, $this->_whitespace, $cursor)); - // grab the key - - $key_begin = $cursor; //we're currently at the start of the key - - // scroll past all characters that are the key (not whitespace or =) - $cursor += strcspn($string, $this->_whitespace . '=', $cursor); - - $key_end = $cursor; // now at the end of the key - - $key = substr($string, $key_begin, $key_end - $key_begin); - - if (!$key) { - if ($e) { - $e->send(E_ERROR, 'Lexer: Missing attribute key'); - } - $cursor += 1 + strcspn($string, $this->_whitespace, $cursor + 1); // prevent infinite loop - continue; // empty key - } - - // scroll past all whitespace - $cursor += strspn($string, $this->_whitespace, $cursor); - - if ($cursor >= $size) { - $array[$key] = $key; - break; - } - - // if the next character is an equal sign, we've got a regular - // pair, otherwise, it's a bool attribute - $first_char = @$string[$cursor]; - - if ($first_char == '=') { - // key="value" - - $cursor++; - $cursor += strspn($string, $this->_whitespace, $cursor); - - if ($cursor === false) { - $array[$key] = ''; - break; - } - - // we might be in front of a quote right now - - $char = @$string[$cursor]; - - if ($char == '"' || $char == "'") { - // it's quoted, end bound is $char - $cursor++; - $value_begin = $cursor; - $cursor = strpos($string, $char, $cursor); - $value_end = $cursor; - } else { - // it's not quoted, end bound is whitespace - $value_begin = $cursor; - $cursor += strcspn($string, $this->_whitespace, $cursor); - $value_end = $cursor; - } - - // we reached a premature end - if ($cursor === false) { - $cursor = $size; - $value_end = $cursor; - } - - $value = substr($string, $value_begin, $value_end - $value_begin); - if ($value === false) { - $value = ''; - } - $array[$key] = $this->parseData($value); - $cursor++; - } else { - // boolattr - if ($key !== '') { - $array[$key] = $key; - } else { - // purely theoretical - if ($e) { - $e->send(E_ERROR, 'Lexer: Missing attribute key'); - } - } - } - } - return $array; - } -} - - - - - -/** - * Concrete comment node class. - */ -class HTMLPurifier_Node_Comment extends HTMLPurifier_Node -{ - /** - * Character data within comment. - * @type string - */ - public $data; - - /** - * @type bool - */ - public $is_whitespace = true; - - /** - * Transparent constructor. - * - * @param string $data String comment data. - * @param int $line - * @param int $col - */ - public function __construct($data, $line = null, $col = null) - { - $this->data = $data; - $this->line = $line; - $this->col = $col; - } - - public function toTokenPair() { - return array(new HTMLPurifier_Token_Comment($this->data, $this->line, $this->col), null); - } -} - - - -/** - * Concrete element node class. - */ -class HTMLPurifier_Node_Element extends HTMLPurifier_Node -{ - /** - * The lower-case name of the tag, like 'a', 'b' or 'blockquote'. - * - * @note Strictly speaking, XML tags are case sensitive, so we shouldn't - * be lower-casing them, but these tokens cater to HTML tags, which are - * insensitive. - * @type string - */ - public $name; - - /** - * Associative array of the node's attributes. - * @type array - */ - public $attr = array(); - - /** - * List of child elements. - * @type array - */ - public $children = array(); - - /** - * Does this use the form or the form, i.e. - * is it a pair of start/end tokens or an empty token. - * @bool - */ - public $empty = false; - - public $endCol = null, $endLine = null, $endArmor = array(); - - public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array()) { - $this->name = $name; - $this->attr = $attr; - $this->line = $line; - $this->col = $col; - $this->armor = $armor; - } - - public function toTokenPair() { - // XXX inefficiency here, normalization is not necessary - if ($this->empty) { - return array(new HTMLPurifier_Token_Empty($this->name, $this->attr, $this->line, $this->col, $this->armor), null); - } else { - $start = new HTMLPurifier_Token_Start($this->name, $this->attr, $this->line, $this->col, $this->armor); - $end = new HTMLPurifier_Token_End($this->name, array(), $this->endLine, $this->endCol, $this->endArmor); - //$end->start = $start; - return array($start, $end); - } - } -} - - - - -/** - * Concrete text token class. - * - * Text tokens comprise of regular parsed character data (PCDATA) and raw - * character data (from the CDATA sections). Internally, their - * data is parsed with all entities expanded. Surprisingly, the text token - * does have a "tag name" called #PCDATA, which is how the DTD represents it - * in permissible child nodes. - */ -class HTMLPurifier_Node_Text extends HTMLPurifier_Node -{ - - /** - * PCDATA tag name compatible with DTD, see - * HTMLPurifier_ChildDef_Custom for details. - * @type string - */ - public $name = '#PCDATA'; - - /** - * @type string - */ - public $data; - /**< Parsed character data of text. */ - - /** - * @type bool - */ - public $is_whitespace; - - /**< Bool indicating if node is whitespace. */ - - /** - * Constructor, accepts data and determines if it is whitespace. - * @param string $data String parsed character data. - * @param int $line - * @param int $col - */ - public function __construct($data, $is_whitespace, $line = null, $col = null) - { - $this->data = $data; - $this->is_whitespace = $is_whitespace; - $this->line = $line; - $this->col = $col; - } - - public function toTokenPair() { - return array(new HTMLPurifier_Token_Text($this->data, $this->line, $this->col), null); - } -} - - - - - -/** - * Composite strategy that runs multiple strategies on tokens. - */ -abstract class HTMLPurifier_Strategy_Composite extends HTMLPurifier_Strategy -{ - - /** - * List of strategies to run tokens through. - * @type HTMLPurifier_Strategy[] - */ - protected $strategies = array(); - - /** - * @param HTMLPurifier_Token[] $tokens - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return HTMLPurifier_Token[] - */ - public function execute($tokens, $config, $context) - { - foreach ($this->strategies as $strategy) { - $tokens = $strategy->execute($tokens, $config, $context); - } - return $tokens; - } -} - - - - - -/** - * Core strategy composed of the big four strategies. - */ -class HTMLPurifier_Strategy_Core extends HTMLPurifier_Strategy_Composite -{ - public function __construct() - { - $this->strategies[] = new HTMLPurifier_Strategy_RemoveForeignElements(); - $this->strategies[] = new HTMLPurifier_Strategy_MakeWellFormed(); - $this->strategies[] = new HTMLPurifier_Strategy_FixNesting(); - $this->strategies[] = new HTMLPurifier_Strategy_ValidateAttributes(); - } -} - - - - - -/** - * Takes a well formed list of tokens and fixes their nesting. - * - * HTML elements dictate which elements are allowed to be their children, - * for example, you can't have a p tag in a span tag. Other elements have - * much more rigorous definitions: tables, for instance, require a specific - * order for their elements. There are also constraints not expressible by - * document type definitions, such as the chameleon nature of ins/del - * tags and global child exclusions. - * - * The first major objective of this strategy is to iterate through all - * the nodes and determine whether or not their children conform to the - * element's definition. If they do not, the child definition may - * optionally supply an amended list of elements that is valid or - * require that the entire node be deleted (and the previous node - * rescanned). - * - * The second objective is to ensure that explicitly excluded elements of - * an element do not appear in its children. Code that accomplishes this - * task is pervasive through the strategy, though the two are distinct tasks - * and could, theoretically, be seperated (although it's not recommended). - * - * @note Whether or not unrecognized children are silently dropped or - * translated into text depends on the child definitions. - * - * @todo Enable nodes to be bubbled out of the structure. This is - * easier with our new algorithm. - */ - -class HTMLPurifier_Strategy_FixNesting extends HTMLPurifier_Strategy -{ - - /** - * @param HTMLPurifier_Token[] $tokens - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return array|HTMLPurifier_Token[] - */ - public function execute($tokens, $config, $context) - { - - //####################################################################// - // Pre-processing - - // O(n) pass to convert to a tree, so that we can efficiently - // refer to substrings - $top_node = HTMLPurifier_Arborize::arborize($tokens, $config, $context); - - // get a copy of the HTML definition - $definition = $config->getHTMLDefinition(); - - $excludes_enabled = !$config->get('Core.DisableExcludes'); - - // setup the context variable 'IsInline', for chameleon processing - // is 'false' when we are not inline, 'true' when it must always - // be inline, and an integer when it is inline for a certain - // branch of the document tree - $is_inline = $definition->info_parent_def->descendants_are_inline; - $context->register('IsInline', $is_inline); - - // setup error collector - $e =& $context->get('ErrorCollector', true); - - //####################################################################// - // Loop initialization - - // stack that contains all elements that are excluded - // it is organized by parent elements, similar to $stack, - // but it is only populated when an element with exclusions is - // processed, i.e. there won't be empty exclusions. - $exclude_stack = array($definition->info_parent_def->excludes); - - // variable that contains the start token while we are processing - // nodes. This enables error reporting to do its job - $node = $top_node; - // dummy token - list($token, $d) = $node->toTokenPair(); - $context->register('CurrentNode', $node); - $context->register('CurrentToken', $token); - - //####################################################################// - // Loop - - // We need to implement a post-order traversal iteratively, to - // avoid running into stack space limits. This is pretty tricky - // to reason about, so we just manually stack-ify the recursive - // variant: - // - // function f($node) { - // foreach ($node->children as $child) { - // f($child); - // } - // validate($node); - // } - // - // Thus, we will represent a stack frame as array($node, - // $is_inline, stack of children) - // e.g. array_reverse($node->children) - already processed - // children. - - $parent_def = $definition->info_parent_def; - $stack = array( - array($top_node, - $parent_def->descendants_are_inline, - $parent_def->excludes, // exclusions - 0) - ); - - while (!empty($stack)) { - list($node, $is_inline, $excludes, $ix) = array_pop($stack); - // recursive call - $go = false; - $def = empty($stack) ? $definition->info_parent_def : $definition->info[$node->name]; - while (isset($node->children[$ix])) { - $child = $node->children[$ix++]; - if ($child instanceof HTMLPurifier_Node_Element) { - $go = true; - $stack[] = array($node, $is_inline, $excludes, $ix); - $stack[] = array($child, - // ToDo: I don't think it matters if it's def or - // child_def, but double check this... - $is_inline || $def->descendants_are_inline, - empty($def->excludes) ? $excludes - : array_merge($excludes, $def->excludes), - 0); - break; - } - }; - if ($go) continue; - list($token, $d) = $node->toTokenPair(); - // base case - if ($excludes_enabled && isset($excludes[$node->name])) { - $node->dead = true; - if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded'); - } else { - // XXX I suppose it would be slightly more efficient to - // avoid the allocation here and have children - // strategies handle it - $children = array(); - foreach ($node->children as $child) { - if (!$child->dead) $children[] = $child; - } - $result = $def->child->validateChildren($children, $config, $context); - if ($result === true) { - // nop - $node->children = $children; - } elseif ($result === false) { - $node->dead = true; - if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node removed'); - } else { - $node->children = $result; - if ($e) { - // XXX This will miss mutations of internal nodes. Perhaps defer to the child validators - if (empty($result) && !empty($children)) { - $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed'); - } elseif ($result != $children) { - $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized'); - } - } - } - } - } - - //####################################################################// - // Post-processing - - // remove context variables - $context->destroy('IsInline'); - $context->destroy('CurrentNode'); - $context->destroy('CurrentToken'); - - //####################################################################// - // Return - - return HTMLPurifier_Arborize::flatten($node, $config, $context); - } -} - - - - - -/** - * Takes tokens makes them well-formed (balance end tags, etc.) - * - * Specification of the armor attributes this strategy uses: - * - * - MakeWellFormed_TagClosedError: This armor field is used to - * suppress tag closed errors for certain tokens [TagClosedSuppress], - * in particular, if a tag was generated automatically by HTML - * Purifier, we may rely on our infrastructure to close it for us - * and shouldn't report an error to the user [TagClosedAuto]. - */ -class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy -{ - - /** - * Array stream of tokens being processed. - * @type HTMLPurifier_Token[] - */ - protected $tokens; - - /** - * Current token. - * @type HTMLPurifier_Token - */ - protected $token; - - /** - * Zipper managing the true state. - * @type HTMLPurifier_Zipper - */ - protected $zipper; - - /** - * Current nesting of elements. - * @type array - */ - protected $stack; - - /** - * Injectors active in this stream processing. - * @type HTMLPurifier_Injector[] - */ - protected $injectors; - - /** - * Current instance of HTMLPurifier_Config. - * @type HTMLPurifier_Config - */ - protected $config; - - /** - * Current instance of HTMLPurifier_Context. - * @type HTMLPurifier_Context - */ - protected $context; - - /** - * @param HTMLPurifier_Token[] $tokens - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return HTMLPurifier_Token[] - * @throws HTMLPurifier_Exception - */ - public function execute($tokens, $config, $context) - { - $definition = $config->getHTMLDefinition(); - - // local variables - $generator = new HTMLPurifier_Generator($config, $context); - $escape_invalid_tags = $config->get('Core.EscapeInvalidTags'); - // used for autoclose early abortion - $global_parent_allowed_elements = $definition->info_parent_def->child->getAllowedElements($config); - $e = $context->get('ErrorCollector', true); - $i = false; // injector index - list($zipper, $token) = HTMLPurifier_Zipper::fromArray($tokens); - if ($token === null) { - return array(); - } - $reprocess = false; // whether or not to reprocess the same token - $stack = array(); - - // member variables - $this->stack =& $stack; - $this->tokens =& $tokens; - $this->token =& $token; - $this->zipper =& $zipper; - $this->config = $config; - $this->context = $context; - - // context variables - $context->register('CurrentNesting', $stack); - $context->register('InputZipper', $zipper); - $context->register('CurrentToken', $token); - - // -- begin INJECTOR -- - - $this->injectors = array(); - - $injectors = $config->getBatch('AutoFormat'); - $def_injectors = $definition->info_injector; - $custom_injectors = $injectors['Custom']; - unset($injectors['Custom']); // special case - foreach ($injectors as $injector => $b) { - // XXX: Fix with a legitimate lookup table of enabled filters - if (strpos($injector, '.') !== false) { - continue; - } - $injector = "HTMLPurifier_Injector_$injector"; - if (!$b) { - continue; - } - $this->injectors[] = new $injector; - } - foreach ($def_injectors as $injector) { - // assumed to be objects - $this->injectors[] = $injector; - } - foreach ($custom_injectors as $injector) { - if (!$injector) { - continue; - } - if (is_string($injector)) { - $injector = "HTMLPurifier_Injector_$injector"; - $injector = new $injector; - } - $this->injectors[] = $injector; - } - - // give the injectors references to the definition and context - // variables for performance reasons - foreach ($this->injectors as $ix => $injector) { - $error = $injector->prepare($config, $context); - if (!$error) { - continue; - } - array_splice($this->injectors, $ix, 1); // rm the injector - trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING); - } - - // -- end INJECTOR -- - - // a note on reprocessing: - // In order to reduce code duplication, whenever some code needs - // to make HTML changes in order to make things "correct", the - // new HTML gets sent through the purifier, regardless of its - // status. This means that if we add a start token, because it - // was totally necessary, we don't have to update nesting; we just - // punt ($reprocess = true; continue;) and it does that for us. - - // isset is in loop because $tokens size changes during loop exec - for (;; - // only increment if we don't need to reprocess - $reprocess ? $reprocess = false : $token = $zipper->next($token)) { - - // check for a rewind - if (is_int($i)) { - // possibility: disable rewinding if the current token has a - // rewind set on it already. This would offer protection from - // infinite loop, but might hinder some advanced rewinding. - $rewind_offset = $this->injectors[$i]->getRewindOffset(); - if (is_int($rewind_offset)) { - for ($j = 0; $j < $rewind_offset; $j++) { - if (empty($zipper->front)) break; - $token = $zipper->prev($token); - // indicate that other injectors should not process this token, - // but we need to reprocess it - unset($token->skip[$i]); - $token->rewind = $i; - if ($token instanceof HTMLPurifier_Token_Start) { - array_pop($this->stack); - } elseif ($token instanceof HTMLPurifier_Token_End) { - $this->stack[] = $token->start; - } - } - } - $i = false; - } - - // handle case of document end - if ($token === null) { - // kill processing if stack is empty - if (empty($this->stack)) { - break; - } - - // peek - $top_nesting = array_pop($this->stack); - $this->stack[] = $top_nesting; - - // send error [TagClosedSuppress] - if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) { - $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting); - } - - // append, don't splice, since this is the end - $token = new HTMLPurifier_Token_End($top_nesting->name); - - // punt! - $reprocess = true; - continue; - } - - //echo '
'; printZipper($zipper, $token);//printTokens($this->stack); - //flush(); - - // quick-check: if it's not a tag, no need to process - if (empty($token->is_tag)) { - if ($token instanceof HTMLPurifier_Token_Text) { - foreach ($this->injectors as $i => $injector) { - if (isset($token->skip[$i])) { - continue; - } - if ($token->rewind !== null && $token->rewind !== $i) { - continue; - } - // XXX fuckup - $r = $token; - $injector->handleText($r); - $token = $this->processToken($r, $i); - $reprocess = true; - break; - } - } - // another possibility is a comment - continue; - } - - if (isset($definition->info[$token->name])) { - $type = $definition->info[$token->name]->child->type; - } else { - $type = false; // Type is unknown, treat accordingly - } - - // quick tag checks: anything that's *not* an end tag - $ok = false; - if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) { - // claims to be a start tag but is empty - $token = new HTMLPurifier_Token_Empty( - $token->name, - $token->attr, - $token->line, - $token->col, - $token->armor - ); - $ok = true; - } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) { - // claims to be empty but really is a start tag - // NB: this assignment is required - $old_token = $token; - $token = new HTMLPurifier_Token_End($token->name); - $token = $this->insertBefore( - new HTMLPurifier_Token_Start($old_token->name, $old_token->attr, $old_token->line, $old_token->col, $old_token->armor) - ); - // punt (since we had to modify the input stream in a non-trivial way) - $reprocess = true; - continue; - } elseif ($token instanceof HTMLPurifier_Token_Empty) { - // real empty token - $ok = true; - } elseif ($token instanceof HTMLPurifier_Token_Start) { - // start tag - - // ...unless they also have to close their parent - if (!empty($this->stack)) { - - // Performance note: you might think that it's rather - // inefficient, recalculating the autoclose information - // for every tag that a token closes (since when we - // do an autoclose, we push a new token into the - // stream and then /process/ that, before - // re-processing this token.) But this is - // necessary, because an injector can make an - // arbitrary transformations to the autoclosing - // tokens we introduce, so things may have changed - // in the meantime. Also, doing the inefficient thing is - // "easy" to reason about (for certain perverse definitions - // of "easy") - - $parent = array_pop($this->stack); - $this->stack[] = $parent; - - $parent_def = null; - $parent_elements = null; - $autoclose = false; - if (isset($definition->info[$parent->name])) { - $parent_def = $definition->info[$parent->name]; - $parent_elements = $parent_def->child->getAllowedElements($config); - $autoclose = !isset($parent_elements[$token->name]); - } - - if ($autoclose && $definition->info[$token->name]->wrap) { - // Check if an element can be wrapped by another - // element to make it valid in a context (for - // example,
      needs a
    • in between) - $wrapname = $definition->info[$token->name]->wrap; - $wrapdef = $definition->info[$wrapname]; - $elements = $wrapdef->child->getAllowedElements($config); - if (isset($elements[$token->name]) && isset($parent_elements[$wrapname])) { - $newtoken = new HTMLPurifier_Token_Start($wrapname); - $token = $this->insertBefore($newtoken); - $reprocess = true; - continue; - } - } - - $carryover = false; - if ($autoclose && $parent_def->formatting) { - $carryover = true; - } - - if ($autoclose) { - // check if this autoclose is doomed to fail - // (this rechecks $parent, which his harmless) - $autoclose_ok = isset($global_parent_allowed_elements[$token->name]); - if (!$autoclose_ok) { - foreach ($this->stack as $ancestor) { - $elements = $definition->info[$ancestor->name]->child->getAllowedElements($config); - if (isset($elements[$token->name])) { - $autoclose_ok = true; - break; - } - if ($definition->info[$token->name]->wrap) { - $wrapname = $definition->info[$token->name]->wrap; - $wrapdef = $definition->info[$wrapname]; - $wrap_elements = $wrapdef->child->getAllowedElements($config); - if (isset($wrap_elements[$token->name]) && isset($elements[$wrapname])) { - $autoclose_ok = true; - break; - } - } - } - } - if ($autoclose_ok) { - // errors need to be updated - $new_token = new HTMLPurifier_Token_End($parent->name); - $new_token->start = $parent; - // [TagClosedSuppress] - if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) { - if (!$carryover) { - $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent); - } else { - $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent); - } - } - if ($carryover) { - $element = clone $parent; - // [TagClosedAuto] - $element->armor['MakeWellFormed_TagClosedError'] = true; - $element->carryover = true; - $token = $this->processToken(array($new_token, $token, $element)); - } else { - $token = $this->insertBefore($new_token); - } - } else { - $token = $this->remove(); - } - $reprocess = true; - continue; - } - - } - $ok = true; - } - - if ($ok) { - foreach ($this->injectors as $i => $injector) { - if (isset($token->skip[$i])) { - continue; - } - if ($token->rewind !== null && $token->rewind !== $i) { - continue; - } - $r = $token; - $injector->handleElement($r); - $token = $this->processToken($r, $i); - $reprocess = true; - break; - } - if (!$reprocess) { - // ah, nothing interesting happened; do normal processing - if ($token instanceof HTMLPurifier_Token_Start) { - $this->stack[] = $token; - } elseif ($token instanceof HTMLPurifier_Token_End) { - throw new HTMLPurifier_Exception( - 'Improper handling of end tag in start code; possible error in MakeWellFormed' - ); - } - } - continue; - } - - // sanity check: we should be dealing with a closing tag - if (!$token instanceof HTMLPurifier_Token_End) { - throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier'); - } - - // make sure that we have something open - if (empty($this->stack)) { - if ($escape_invalid_tags) { - if ($e) { - $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text'); - } - $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token)); - } else { - if ($e) { - $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed'); - } - $token = $this->remove(); - } - $reprocess = true; - continue; - } - - // first, check for the simplest case: everything closes neatly. - // Eventually, everything passes through here; if there are problems - // we modify the input stream accordingly and then punt, so that - // the tokens get processed again. - $current_parent = array_pop($this->stack); - if ($current_parent->name == $token->name) { - $token->start = $current_parent; - foreach ($this->injectors as $i => $injector) { - if (isset($token->skip[$i])) { - continue; - } - if ($token->rewind !== null && $token->rewind !== $i) { - continue; - } - $r = $token; - $injector->handleEnd($r); - $token = $this->processToken($r, $i); - $this->stack[] = $current_parent; - $reprocess = true; - break; - } - continue; - } - - // okay, so we're trying to close the wrong tag - - // undo the pop previous pop - $this->stack[] = $current_parent; - - // scroll back the entire nest, trying to find our tag. - // (feature could be to specify how far you'd like to go) - $size = count($this->stack); - // -2 because -1 is the last element, but we already checked that - $skipped_tags = false; - for ($j = $size - 2; $j >= 0; $j--) { - if ($this->stack[$j]->name == $token->name) { - $skipped_tags = array_slice($this->stack, $j); - break; - } - } - - // we didn't find the tag, so remove - if ($skipped_tags === false) { - if ($escape_invalid_tags) { - if ($e) { - $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text'); - } - $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token)); - } else { - if ($e) { - $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed'); - } - $token = $this->remove(); - } - $reprocess = true; - continue; - } - - // do errors, in REVERSE $j order: a,b,c with - $c = count($skipped_tags); - if ($e) { - for ($j = $c - 1; $j > 0; $j--) { - // notice we exclude $j == 0, i.e. the current ending tag, from - // the errors... [TagClosedSuppress] - if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) { - $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]); - } - } - } - - // insert tags, in FORWARD $j order: c,b,a with - $replace = array($token); - for ($j = 1; $j < $c; $j++) { - // ...as well as from the insertions - $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name); - $new_token->start = $skipped_tags[$j]; - array_unshift($replace, $new_token); - if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) { - // [TagClosedAuto] - $element = clone $skipped_tags[$j]; - $element->carryover = true; - $element->armor['MakeWellFormed_TagClosedError'] = true; - $replace[] = $element; - } - } - $token = $this->processToken($replace); - $reprocess = true; - continue; - } - - $context->destroy('CurrentToken'); - $context->destroy('CurrentNesting'); - $context->destroy('InputZipper'); - - unset($this->injectors, $this->stack, $this->tokens); - return $zipper->toArray($token); - } - - /** - * Processes arbitrary token values for complicated substitution patterns. - * In general: - * - * If $token is an array, it is a list of tokens to substitute for the - * current token. These tokens then get individually processed. If there - * is a leading integer in the list, that integer determines how many - * tokens from the stream should be removed. - * - * If $token is a regular token, it is swapped with the current token. - * - * If $token is false, the current token is deleted. - * - * If $token is an integer, that number of tokens (with the first token - * being the current one) will be deleted. - * - * @param HTMLPurifier_Token|array|int|bool $token Token substitution value - * @param HTMLPurifier_Injector|int $injector Injector that performed the substitution; default is if - * this is not an injector related operation. - * @throws HTMLPurifier_Exception - */ - protected function processToken($token, $injector = -1) - { - // normalize forms of token - if (is_object($token)) { - $token = array(1, $token); - } - if (is_int($token)) { - $token = array($token); - } - if ($token === false) { - $token = array(1); - } - if (!is_array($token)) { - throw new HTMLPurifier_Exception('Invalid token type from injector'); - } - if (!is_int($token[0])) { - array_unshift($token, 1); - } - if ($token[0] === 0) { - throw new HTMLPurifier_Exception('Deleting zero tokens is not valid'); - } - - // $token is now an array with the following form: - // array(number nodes to delete, new node 1, new node 2, ...) - - $delete = array_shift($token); - list($old, $r) = $this->zipper->splice($this->token, $delete, $token); - - if ($injector > -1) { - // determine appropriate skips - $oldskip = isset($old[0]) ? $old[0]->skip : array(); - foreach ($token as $object) { - $object->skip = $oldskip; - $object->skip[$injector] = true; - } - } - - return $r; - - } - - /** - * Inserts a token before the current token. Cursor now points to - * this token. You must reprocess after this. - * @param HTMLPurifier_Token $token - */ - private function insertBefore($token) - { - // NB not $this->zipper->insertBefore(), due to positioning - // differences - $splice = $this->zipper->splice($this->token, 0, array($token)); - - return $splice[1]; - } - - /** - * Removes current token. Cursor now points to new token occupying previously - * occupied space. You must reprocess after this. - */ - private function remove() - { - return $this->zipper->delete(); - } -} - - - - - -/** - * Removes all unrecognized tags from the list of tokens. - * - * This strategy iterates through all the tokens and removes unrecognized - * tokens. If a token is not recognized but a TagTransform is defined for - * that element, the element will be transformed accordingly. - */ - -class HTMLPurifier_Strategy_RemoveForeignElements extends HTMLPurifier_Strategy -{ - - /** - * @param HTMLPurifier_Token[] $tokens - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return array|HTMLPurifier_Token[] - */ - public function execute($tokens, $config, $context) - { - $definition = $config->getHTMLDefinition(); - $generator = new HTMLPurifier_Generator($config, $context); - $result = array(); - - $escape_invalid_tags = $config->get('Core.EscapeInvalidTags'); - $remove_invalid_img = $config->get('Core.RemoveInvalidImg'); - - // currently only used to determine if comments should be kept - $trusted = $config->get('HTML.Trusted'); - $comment_lookup = $config->get('HTML.AllowedComments'); - $comment_regexp = $config->get('HTML.AllowedCommentsRegexp'); - $check_comments = $comment_lookup !== array() || $comment_regexp !== null; - - $remove_script_contents = $config->get('Core.RemoveScriptContents'); - $hidden_elements = $config->get('Core.HiddenElements'); - - // remove script contents compatibility - if ($remove_script_contents === true) { - $hidden_elements['script'] = true; - } elseif ($remove_script_contents === false && isset($hidden_elements['script'])) { - unset($hidden_elements['script']); - } - - $attr_validator = new HTMLPurifier_AttrValidator(); - - // removes tokens until it reaches a closing tag with its value - $remove_until = false; - - // converts comments into text tokens when this is equal to a tag name - $textify_comments = false; - - $token = false; - $context->register('CurrentToken', $token); - - $e = false; - if ($config->get('Core.CollectErrors')) { - $e =& $context->get('ErrorCollector'); - } - - foreach ($tokens as $token) { - if ($remove_until) { - if (empty($token->is_tag) || $token->name !== $remove_until) { - continue; - } - } - if (!empty($token->is_tag)) { - // DEFINITION CALL - - // before any processing, try to transform the element - if (isset($definition->info_tag_transform[$token->name])) { - $original_name = $token->name; - // there is a transformation for this tag - // DEFINITION CALL - $token = $definition-> - info_tag_transform[$token->name]->transform($token, $config, $context); - if ($e) { - $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Tag transform', $original_name); - } - } - - if (isset($definition->info[$token->name])) { - // mostly everything's good, but - // we need to make sure required attributes are in order - if (($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) && - $definition->info[$token->name]->required_attr && - ($token->name != 'img' || $remove_invalid_img) // ensure config option still works - ) { - $attr_validator->validateToken($token, $config, $context); - $ok = true; - foreach ($definition->info[$token->name]->required_attr as $name) { - if (!isset($token->attr[$name])) { - $ok = false; - break; - } - } - if (!$ok) { - if ($e) { - $e->send( - E_ERROR, - 'Strategy_RemoveForeignElements: Missing required attribute', - $name - ); - } - continue; - } - $token->armor['ValidateAttributes'] = true; - } - - if (isset($hidden_elements[$token->name]) && $token instanceof HTMLPurifier_Token_Start) { - $textify_comments = $token->name; - } elseif ($token->name === $textify_comments && $token instanceof HTMLPurifier_Token_End) { - $textify_comments = false; - } - - } elseif ($escape_invalid_tags) { - // invalid tag, generate HTML representation and insert in - if ($e) { - $e->send(E_WARNING, 'Strategy_RemoveForeignElements: Foreign element to text'); - } - $token = new HTMLPurifier_Token_Text( - $generator->generateFromToken($token) - ); - } else { - // check if we need to destroy all of the tag's children - // CAN BE GENERICIZED - if (isset($hidden_elements[$token->name])) { - if ($token instanceof HTMLPurifier_Token_Start) { - $remove_until = $token->name; - } elseif ($token instanceof HTMLPurifier_Token_Empty) { - // do nothing: we're still looking - } else { - $remove_until = false; - } - if ($e) { - $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign meta element removed'); - } - } else { - if ($e) { - $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign element removed'); - } - } - continue; - } - } elseif ($token instanceof HTMLPurifier_Token_Comment) { - // textify comments in script tags when they are allowed - if ($textify_comments !== false) { - $data = $token->data; - $token = new HTMLPurifier_Token_Text($data); - } elseif ($trusted || $check_comments) { - // always cleanup comments - $trailing_hyphen = false; - if ($e) { - // perform check whether or not there's a trailing hyphen - if (substr($token->data, -1) == '-') { - $trailing_hyphen = true; - } - } - $token->data = rtrim($token->data, '-'); - $found_double_hyphen = false; - while (strpos($token->data, '--') !== false) { - $found_double_hyphen = true; - $token->data = str_replace('--', '-', $token->data); - } - if ($trusted || !empty($comment_lookup[trim($token->data)]) || - ($comment_regexp !== null && preg_match($comment_regexp, trim($token->data)))) { - // OK good - if ($e) { - if ($trailing_hyphen) { - $e->send( - E_NOTICE, - 'Strategy_RemoveForeignElements: Trailing hyphen in comment removed' - ); - } - if ($found_double_hyphen) { - $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Hyphens in comment collapsed'); - } - } - } else { - if ($e) { - $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed'); - } - continue; - } - } else { - // strip comments - if ($e) { - $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed'); - } - continue; - } - } elseif ($token instanceof HTMLPurifier_Token_Text) { - } else { - continue; - } - $result[] = $token; - } - if ($remove_until && $e) { - // we removed tokens until the end, throw error - $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Token removed to end', $remove_until); - } - $context->destroy('CurrentToken'); - return $result; - } -} - - - - - -/** - * Validate all attributes in the tokens. - */ - -class HTMLPurifier_Strategy_ValidateAttributes extends HTMLPurifier_Strategy -{ - - /** - * @param HTMLPurifier_Token[] $tokens - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return HTMLPurifier_Token[] - */ - public function execute($tokens, $config, $context) - { - // setup validator - $validator = new HTMLPurifier_AttrValidator(); - - $token = false; - $context->register('CurrentToken', $token); - - foreach ($tokens as $key => $token) { - - // only process tokens that have attributes, - // namely start and empty tags - if (!$token instanceof HTMLPurifier_Token_Start && !$token instanceof HTMLPurifier_Token_Empty) { - continue; - } - - // skip tokens that are armored - if (!empty($token->armor['ValidateAttributes'])) { - continue; - } - - // note that we have no facilities here for removing tokens - $validator->validateToken($token, $config, $context); - } - $context->destroy('CurrentToken'); - return $tokens; - } -} - - - - - -/** - * Transforms FONT tags to the proper form (SPAN with CSS styling) - * - * This transformation takes the three proprietary attributes of FONT and - * transforms them into their corresponding CSS attributes. These are color, - * face, and size. - * - * @note Size is an interesting case because it doesn't map cleanly to CSS. - * Thanks to - * http://style.cleverchimp.com/font_size_intervals/altintervals.html - * for reasonable mappings. - * @warning This doesn't work completely correctly; specifically, this - * TagTransform operates before well-formedness is enforced, so - * the "active formatting elements" algorithm doesn't get applied. - */ -class HTMLPurifier_TagTransform_Font extends HTMLPurifier_TagTransform -{ - /** - * @type string - */ - public $transform_to = 'span'; - - /** - * @type array - */ - protected $_size_lookup = array( - '0' => 'xx-small', - '1' => 'xx-small', - '2' => 'small', - '3' => 'medium', - '4' => 'large', - '5' => 'x-large', - '6' => 'xx-large', - '7' => '300%', - '-1' => 'smaller', - '-2' => '60%', - '+1' => 'larger', - '+2' => '150%', - '+3' => '200%', - '+4' => '300%' - ); - - /** - * @param HTMLPurifier_Token_Tag $tag - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return HTMLPurifier_Token_End|string - */ - public function transform($tag, $config, $context) - { - if ($tag instanceof HTMLPurifier_Token_End) { - $new_tag = clone $tag; - $new_tag->name = $this->transform_to; - return $new_tag; - } - - $attr = $tag->attr; - $prepend_style = ''; - - // handle color transform - if (isset($attr['color'])) { - $prepend_style .= 'color:' . $attr['color'] . ';'; - unset($attr['color']); - } - - // handle face transform - if (isset($attr['face'])) { - $prepend_style .= 'font-family:' . $attr['face'] . ';'; - unset($attr['face']); - } - - // handle size transform - if (isset($attr['size'])) { - // normalize large numbers - if ($attr['size'] !== '') { - if ($attr['size']{0} == '+' || $attr['size']{0} == '-') { - $size = (int)$attr['size']; - if ($size < -2) { - $attr['size'] = '-2'; - } - if ($size > 4) { - $attr['size'] = '+4'; - } - } else { - $size = (int)$attr['size']; - if ($size > 7) { - $attr['size'] = '7'; - } - } - } - if (isset($this->_size_lookup[$attr['size']])) { - $prepend_style .= 'font-size:' . - $this->_size_lookup[$attr['size']] . ';'; - } - unset($attr['size']); - } - - if ($prepend_style) { - $attr['style'] = isset($attr['style']) ? - $prepend_style . $attr['style'] : - $prepend_style; - } - - $new_tag = clone $tag; - $new_tag->name = $this->transform_to; - $new_tag->attr = $attr; - - return $new_tag; - } -} - - - - - -/** - * Simple transformation, just change tag name to something else, - * and possibly add some styling. This will cover most of the deprecated - * tag cases. - */ -class HTMLPurifier_TagTransform_Simple extends HTMLPurifier_TagTransform -{ - /** - * @type string - */ - protected $style; - - /** - * @param string $transform_to Tag name to transform to. - * @param string $style CSS style to add to the tag - */ - public function __construct($transform_to, $style = null) - { - $this->transform_to = $transform_to; - $this->style = $style; - } - - /** - * @param HTMLPurifier_Token_Tag $tag - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return string - */ - public function transform($tag, $config, $context) - { - $new_tag = clone $tag; - $new_tag->name = $this->transform_to; - if (!is_null($this->style) && - ($new_tag instanceof HTMLPurifier_Token_Start || $new_tag instanceof HTMLPurifier_Token_Empty) - ) { - $this->prependCSS($new_tag->attr, $this->style); - } - return $new_tag; - } -} - - - - - -/** - * Concrete comment token class. Generally will be ignored. - */ -class HTMLPurifier_Token_Comment extends HTMLPurifier_Token -{ - /** - * Character data within comment. - * @type string - */ - public $data; - - /** - * @type bool - */ - public $is_whitespace = true; - - /** - * Transparent constructor. - * - * @param string $data String comment data. - * @param int $line - * @param int $col - */ - public function __construct($data, $line = null, $col = null) - { - $this->data = $data; - $this->line = $line; - $this->col = $col; - } - - public function toNode() { - return new HTMLPurifier_Node_Comment($this->data, $this->line, $this->col); - } -} - - - - - -/** - * Abstract class of a tag token (start, end or empty), and its behavior. - */ -abstract class HTMLPurifier_Token_Tag extends HTMLPurifier_Token -{ - /** - * Static bool marker that indicates the class is a tag. - * - * This allows us to check objects with !empty($obj->is_tag) - * without having to use a function call is_a(). - * @type bool - */ - public $is_tag = true; - - /** - * The lower-case name of the tag, like 'a', 'b' or 'blockquote'. - * - * @note Strictly speaking, XML tags are case sensitive, so we shouldn't - * be lower-casing them, but these tokens cater to HTML tags, which are - * insensitive. - * @type string - */ - public $name; - - /** - * Associative array of the tag's attributes. - * @type array - */ - public $attr = array(); - - /** - * Non-overloaded constructor, which lower-cases passed tag name. - * - * @param string $name String name. - * @param array $attr Associative array of attributes. - * @param int $line - * @param int $col - * @param array $armor - */ - public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array()) - { - $this->name = ctype_lower($name) ? $name : strtolower($name); - foreach ($attr as $key => $value) { - // normalization only necessary when key is not lowercase - if (!ctype_lower($key)) { - $new_key = strtolower($key); - if (!isset($attr[$new_key])) { - $attr[$new_key] = $attr[$key]; - } - if ($new_key !== $key) { - unset($attr[$key]); - } - } - } - $this->attr = $attr; - $this->line = $line; - $this->col = $col; - $this->armor = $armor; - } - - public function toNode() { - return new HTMLPurifier_Node_Element($this->name, $this->attr, $this->line, $this->col, $this->armor); - } -} - - - - - -/** - * Concrete empty token class. - */ -class HTMLPurifier_Token_Empty extends HTMLPurifier_Token_Tag -{ - public function toNode() { - $n = parent::toNode(); - $n->empty = true; - return $n; - } -} - - - - - -/** - * Concrete end token class. - * - * @warning This class accepts attributes even though end tags cannot. This - * is for optimization reasons, as under normal circumstances, the Lexers - * do not pass attributes. - */ -class HTMLPurifier_Token_End extends HTMLPurifier_Token_Tag -{ - /** - * Token that started this node. - * Added by MakeWellFormed. Please do not edit this! - * @type HTMLPurifier_Token - */ - public $start; - - public function toNode() { - throw new Exception("HTMLPurifier_Token_End->toNode not supported!"); - } -} - - - - - -/** - * Concrete start token class. - */ -class HTMLPurifier_Token_Start extends HTMLPurifier_Token_Tag -{ -} - - - - - -/** - * Concrete text token class. - * - * Text tokens comprise of regular parsed character data (PCDATA) and raw - * character data (from the CDATA sections). Internally, their - * data is parsed with all entities expanded. Surprisingly, the text token - * does have a "tag name" called #PCDATA, which is how the DTD represents it - * in permissible child nodes. - */ -class HTMLPurifier_Token_Text extends HTMLPurifier_Token -{ - - /** - * @type string - */ - public $name = '#PCDATA'; - /**< PCDATA tag name compatible with DTD. */ - - /** - * @type string - */ - public $data; - /**< Parsed character data of text. */ - - /** - * @type bool - */ - public $is_whitespace; - - /**< Bool indicating if node is whitespace. */ - - /** - * Constructor, accepts data and determines if it is whitespace. - * @param string $data String parsed character data. - * @param int $line - * @param int $col - */ - public function __construct($data, $line = null, $col = null) - { - $this->data = $data; - $this->is_whitespace = ctype_space($data); - $this->line = $line; - $this->col = $col; - } - - public function toNode() { - return new HTMLPurifier_Node_Text($this->data, $this->is_whitespace, $this->line, $this->col); - } -} - - - - - -class HTMLPurifier_URIFilter_DisableExternal extends HTMLPurifier_URIFilter -{ - /** - * @type string - */ - public $name = 'DisableExternal'; - - /** - * @type array - */ - protected $ourHostParts = false; - - /** - * @param HTMLPurifier_Config $config - * @return void - */ - public function prepare($config) - { - $our_host = $config->getDefinition('URI')->host; - if ($our_host !== null) { - $this->ourHostParts = array_reverse(explode('.', $our_host)); - } - } - - /** - * @param HTMLPurifier_URI $uri Reference - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function filter(&$uri, $config, $context) - { - if (is_null($uri->host)) { - return true; - } - if ($this->ourHostParts === false) { - return false; - } - $host_parts = array_reverse(explode('.', $uri->host)); - foreach ($this->ourHostParts as $i => $x) { - if (!isset($host_parts[$i])) { - return false; - } - if ($host_parts[$i] != $this->ourHostParts[$i]) { - return false; - } - } - return true; - } -} - - - - - -class HTMLPurifier_URIFilter_DisableExternalResources extends HTMLPurifier_URIFilter_DisableExternal -{ - /** - * @type string - */ - public $name = 'DisableExternalResources'; - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function filter(&$uri, $config, $context) - { - if (!$context->get('EmbeddedURI', true)) { - return true; - } - return parent::filter($uri, $config, $context); - } -} - - - - - -class HTMLPurifier_URIFilter_DisableResources extends HTMLPurifier_URIFilter -{ - /** - * @type string - */ - public $name = 'DisableResources'; - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function filter(&$uri, $config, $context) - { - return !$context->get('EmbeddedURI', true); - } -} - - - - - -// It's not clear to me whether or not Punycode means that hostnames -// do not have canonical forms anymore. As far as I can tell, it's -// not a problem (punycoding should be identity when no Unicode -// points are involved), but I'm not 100% sure -class HTMLPurifier_URIFilter_HostBlacklist extends HTMLPurifier_URIFilter -{ - /** - * @type string - */ - public $name = 'HostBlacklist'; - - /** - * @type array - */ - protected $blacklist = array(); - - /** - * @param HTMLPurifier_Config $config - * @return bool - */ - public function prepare($config) - { - $this->blacklist = $config->get('URI.HostBlacklist'); - return true; - } - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function filter(&$uri, $config, $context) - { - foreach ($this->blacklist as $blacklisted_host_fragment) { - if (strpos($uri->host, $blacklisted_host_fragment) !== false) { - return false; - } - } - return true; - } -} - - - - - -// does not support network paths - -class HTMLPurifier_URIFilter_MakeAbsolute extends HTMLPurifier_URIFilter -{ - /** - * @type string - */ - public $name = 'MakeAbsolute'; - - /** - * @type - */ - protected $base; - - /** - * @type array - */ - protected $basePathStack = array(); - - /** - * @param HTMLPurifier_Config $config - * @return bool - */ - public function prepare($config) - { - $def = $config->getDefinition('URI'); - $this->base = $def->base; - if (is_null($this->base)) { - trigger_error( - 'URI.MakeAbsolute is being ignored due to lack of ' . - 'value for URI.Base configuration', - E_USER_WARNING - ); - return false; - } - $this->base->fragment = null; // fragment is invalid for base URI - $stack = explode('/', $this->base->path); - array_pop($stack); // discard last segment - $stack = $this->_collapseStack($stack); // do pre-parsing - $this->basePathStack = $stack; - return true; - } - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function filter(&$uri, $config, $context) - { - if (is_null($this->base)) { - return true; - } // abort early - if ($uri->path === '' && is_null($uri->scheme) && - is_null($uri->host) && is_null($uri->query) && is_null($uri->fragment)) { - // reference to current document - $uri = clone $this->base; - return true; - } - if (!is_null($uri->scheme)) { - // absolute URI already: don't change - if (!is_null($uri->host)) { - return true; - } - $scheme_obj = $uri->getSchemeObj($config, $context); - if (!$scheme_obj) { - // scheme not recognized - return false; - } - if (!$scheme_obj->hierarchical) { - // non-hierarchal URI with explicit scheme, don't change - return true; - } - // special case: had a scheme but always is hierarchical and had no authority - } - if (!is_null($uri->host)) { - // network path, don't bother - return true; - } - if ($uri->path === '') { - $uri->path = $this->base->path; - } elseif ($uri->path[0] !== '/') { - // relative path, needs more complicated processing - $stack = explode('/', $uri->path); - $new_stack = array_merge($this->basePathStack, $stack); - if ($new_stack[0] !== '' && !is_null($this->base->host)) { - array_unshift($new_stack, ''); - } - $new_stack = $this->_collapseStack($new_stack); - $uri->path = implode('/', $new_stack); - } else { - // absolute path, but still we should collapse - $uri->path = implode('/', $this->_collapseStack(explode('/', $uri->path))); - } - // re-combine - $uri->scheme = $this->base->scheme; - if (is_null($uri->userinfo)) { - $uri->userinfo = $this->base->userinfo; - } - if (is_null($uri->host)) { - $uri->host = $this->base->host; - } - if (is_null($uri->port)) { - $uri->port = $this->base->port; - } - return true; - } - - /** - * Resolve dots and double-dots in a path stack - * @param array $stack - * @return array - */ - private function _collapseStack($stack) - { - $result = array(); - $is_folder = false; - for ($i = 0; isset($stack[$i]); $i++) { - $is_folder = false; - // absorb an internally duplicated slash - if ($stack[$i] == '' && $i && isset($stack[$i + 1])) { - continue; - } - if ($stack[$i] == '..') { - if (!empty($result)) { - $segment = array_pop($result); - if ($segment === '' && empty($result)) { - // error case: attempted to back out too far: - // restore the leading slash - $result[] = ''; - } elseif ($segment === '..') { - $result[] = '..'; // cannot remove .. with .. - } - } else { - // relative path, preserve the double-dots - $result[] = '..'; - } - $is_folder = true; - continue; - } - if ($stack[$i] == '.') { - // silently absorb - $is_folder = true; - continue; - } - $result[] = $stack[$i]; - } - if ($is_folder) { - $result[] = ''; - } - return $result; - } -} - - - - - -class HTMLPurifier_URIFilter_Munge extends HTMLPurifier_URIFilter -{ - /** - * @type string - */ - public $name = 'Munge'; - - /** - * @type bool - */ - public $post = true; - - /** - * @type string - */ - private $target; - - /** - * @type HTMLPurifier_URIParser - */ - private $parser; - - /** - * @type bool - */ - private $doEmbed; - - /** - * @type string - */ - private $secretKey; - - /** - * @type array - */ - protected $replace = array(); - - /** - * @param HTMLPurifier_Config $config - * @return bool - */ - public function prepare($config) - { - $this->target = $config->get('URI.' . $this->name); - $this->parser = new HTMLPurifier_URIParser(); - $this->doEmbed = $config->get('URI.MungeResources'); - $this->secretKey = $config->get('URI.MungeSecretKey'); - if ($this->secretKey && !function_exists('hash_hmac')) { - throw new Exception("Cannot use %URI.MungeSecretKey without hash_hmac support."); - } - return true; - } - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function filter(&$uri, $config, $context) - { - if ($context->get('EmbeddedURI', true) && !$this->doEmbed) { - return true; - } - - $scheme_obj = $uri->getSchemeObj($config, $context); - if (!$scheme_obj) { - return true; - } // ignore unknown schemes, maybe another postfilter did it - if (!$scheme_obj->browsable) { - return true; - } // ignore non-browseable schemes, since we can't munge those in a reasonable way - if ($uri->isBenign($config, $context)) { - return true; - } // don't redirect if a benign URL - - $this->makeReplace($uri, $config, $context); - $this->replace = array_map('rawurlencode', $this->replace); - - $new_uri = strtr($this->target, $this->replace); - $new_uri = $this->parser->parse($new_uri); - // don't redirect if the target host is the same as the - // starting host - if ($uri->host === $new_uri->host) { - return true; - } - $uri = $new_uri; // overwrite - return true; - } - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - */ - protected function makeReplace($uri, $config, $context) - { - $string = $uri->toString(); - // always available - $this->replace['%s'] = $string; - $this->replace['%r'] = $context->get('EmbeddedURI', true); - $token = $context->get('CurrentToken', true); - $this->replace['%n'] = $token ? $token->name : null; - $this->replace['%m'] = $context->get('CurrentAttr', true); - $this->replace['%p'] = $context->get('CurrentCSSProperty', true); - // not always available - if ($this->secretKey) { - $this->replace['%t'] = hash_hmac("sha256", $string, $this->secretKey); - } - } -} - - - - - -/** - * Implements safety checks for safe iframes. - * - * @warning This filter is *critical* for ensuring that %HTML.SafeIframe - * works safely. - */ -class HTMLPurifier_URIFilter_SafeIframe extends HTMLPurifier_URIFilter -{ - /** - * @type string - */ - public $name = 'SafeIframe'; - - /** - * @type bool - */ - public $always_load = true; - - /** - * @type string - */ - protected $regexp = null; - - // XXX: The not so good bit about how this is all set up now is we - // can't check HTML.SafeIframe in the 'prepare' step: we have to - // defer till the actual filtering. - /** - * @param HTMLPurifier_Config $config - * @return bool - */ - public function prepare($config) - { - $this->regexp = $config->get('URI.SafeIframeRegexp'); - return true; - } - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function filter(&$uri, $config, $context) - { - // check if filter not applicable - if (!$config->get('HTML.SafeIframe')) { - return true; - } - // check if the filter should actually trigger - if (!$context->get('EmbeddedURI', true)) { - return true; - } - $token = $context->get('CurrentToken', true); - if (!($token && $token->name == 'iframe')) { - return true; - } - // check if we actually have some whitelists enabled - if ($this->regexp === null) { - return false; - } - // actually check the whitelists - return preg_match($this->regexp, $uri->toString()); - } -} - - - - - -/** - * Implements data: URI for base64 encoded images supported by GD. - */ -class HTMLPurifier_URIScheme_data extends HTMLPurifier_URIScheme -{ - /** - * @type bool - */ - public $browsable = true; - - /** - * @type array - */ - public $allowed_types = array( - // you better write validation code for other types if you - // decide to allow them - 'image/jpeg' => true, - 'image/gif' => true, - 'image/png' => true, - ); - // this is actually irrelevant since we only write out the path - // component - /** - * @type bool - */ - public $may_omit_host = true; - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function doValidate(&$uri, $config, $context) - { - $result = explode(',', $uri->path, 2); - $is_base64 = false; - $charset = null; - $content_type = null; - if (count($result) == 2) { - list($metadata, $data) = $result; - // do some legwork on the metadata - $metas = explode(';', $metadata); - while (!empty($metas)) { - $cur = array_shift($metas); - if ($cur == 'base64') { - $is_base64 = true; - break; - } - if (substr($cur, 0, 8) == 'charset=') { - // doesn't match if there are arbitrary spaces, but - // whatever dude - if ($charset !== null) { - continue; - } // garbage - $charset = substr($cur, 8); // not used - } else { - if ($content_type !== null) { - continue; - } // garbage - $content_type = $cur; - } - } - } else { - $data = $result[0]; - } - if ($content_type !== null && empty($this->allowed_types[$content_type])) { - return false; - } - if ($charset !== null) { - // error; we don't allow plaintext stuff - $charset = null; - } - $data = rawurldecode($data); - if ($is_base64) { - $raw_data = base64_decode($data); - } else { - $raw_data = $data; - } - // XXX probably want to refactor this into a general mechanism - // for filtering arbitrary content types - $file = tempnam("/tmp", ""); - file_put_contents($file, $raw_data); - if (function_exists('exif_imagetype')) { - $image_code = exif_imagetype($file); - unlink($file); - } elseif (function_exists('getimagesize')) { - set_error_handler(array($this, 'muteErrorHandler')); - $info = getimagesize($file); - restore_error_handler(); - unlink($file); - if ($info == false) { - return false; - } - $image_code = $info[2]; - } else { - trigger_error("could not find exif_imagetype or getimagesize functions", E_USER_ERROR); - } - $real_content_type = image_type_to_mime_type($image_code); - if ($real_content_type != $content_type) { - // we're nice guys; if the content type is something else we - // support, change it over - if (empty($this->allowed_types[$real_content_type])) { - return false; - } - $content_type = $real_content_type; - } - // ok, it's kosher, rewrite what we need - $uri->userinfo = null; - $uri->host = null; - $uri->port = null; - $uri->fragment = null; - $uri->query = null; - $uri->path = "$content_type;base64," . base64_encode($raw_data); - return true; - } - - /** - * @param int $errno - * @param string $errstr - */ - public function muteErrorHandler($errno, $errstr) - { - } -} - - - -/** - * Validates file as defined by RFC 1630 and RFC 1738. - */ -class HTMLPurifier_URIScheme_file extends HTMLPurifier_URIScheme -{ - /** - * Generally file:// URLs are not accessible from most - * machines, so placing them as an img src is incorrect. - * @type bool - */ - public $browsable = false; - - /** - * Basically the *only* URI scheme for which this is true, since - * accessing files on the local machine is very common. In fact, - * browsers on some operating systems don't understand the - * authority, though I hear it is used on Windows to refer to - * network shares. - * @type bool - */ - public $may_omit_host = true; - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function doValidate(&$uri, $config, $context) - { - // Authentication method is not supported - $uri->userinfo = null; - // file:// makes no provisions for accessing the resource - $uri->port = null; - // While it seems to work on Firefox, the querystring has - // no possible effect and is thus stripped. - $uri->query = null; - return true; - } -} - - - - - -/** - * Validates ftp (File Transfer Protocol) URIs as defined by generic RFC 1738. - */ -class HTMLPurifier_URIScheme_ftp extends HTMLPurifier_URIScheme -{ - /** - * @type int - */ - public $default_port = 21; - - /** - * @type bool - */ - public $browsable = true; // usually - - /** - * @type bool - */ - public $hierarchical = true; - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function doValidate(&$uri, $config, $context) - { - $uri->query = null; - - // typecode check - $semicolon_pos = strrpos($uri->path, ';'); // reverse - if ($semicolon_pos !== false) { - $type = substr($uri->path, $semicolon_pos + 1); // no semicolon - $uri->path = substr($uri->path, 0, $semicolon_pos); - $type_ret = ''; - if (strpos($type, '=') !== false) { - // figure out whether or not the declaration is correct - list($key, $typecode) = explode('=', $type, 2); - if ($key !== 'type') { - // invalid key, tack it back on encoded - $uri->path .= '%3B' . $type; - } elseif ($typecode === 'a' || $typecode === 'i' || $typecode === 'd') { - $type_ret = ";type=$typecode"; - } - } else { - $uri->path .= '%3B' . $type; - } - $uri->path = str_replace(';', '%3B', $uri->path); - $uri->path .= $type_ret; - } - return true; - } -} - - - - - -/** - * Validates http (HyperText Transfer Protocol) as defined by RFC 2616 - */ -class HTMLPurifier_URIScheme_http extends HTMLPurifier_URIScheme -{ - /** - * @type int - */ - public $default_port = 80; - - /** - * @type bool - */ - public $browsable = true; - - /** - * @type bool - */ - public $hierarchical = true; - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function doValidate(&$uri, $config, $context) - { - $uri->userinfo = null; - return true; - } -} - - - - - -/** - * Validates https (Secure HTTP) according to http scheme. - */ -class HTMLPurifier_URIScheme_https extends HTMLPurifier_URIScheme_http -{ - /** - * @type int - */ - public $default_port = 443; - /** - * @type bool - */ - public $secure = true; -} - - - - - -// VERY RELAXED! Shouldn't cause problems, not even Firefox checks if the -// email is valid, but be careful! - -/** - * Validates mailto (for E-mail) according to RFC 2368 - * @todo Validate the email address - * @todo Filter allowed query parameters - */ - -class HTMLPurifier_URIScheme_mailto extends HTMLPurifier_URIScheme -{ - /** - * @type bool - */ - public $browsable = false; - - /** - * @type bool - */ - public $may_omit_host = true; - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function doValidate(&$uri, $config, $context) - { - $uri->userinfo = null; - $uri->host = null; - $uri->port = null; - // we need to validate path against RFC 2368's addr-spec - return true; - } -} - - - - - -/** - * Validates news (Usenet) as defined by generic RFC 1738 - */ -class HTMLPurifier_URIScheme_news extends HTMLPurifier_URIScheme -{ - /** - * @type bool - */ - public $browsable = false; - - /** - * @type bool - */ - public $may_omit_host = true; - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function doValidate(&$uri, $config, $context) - { - $uri->userinfo = null; - $uri->host = null; - $uri->port = null; - $uri->query = null; - // typecode check needed on path - return true; - } -} - - - - - -/** - * Validates nntp (Network News Transfer Protocol) as defined by generic RFC 1738 - */ -class HTMLPurifier_URIScheme_nntp extends HTMLPurifier_URIScheme -{ - /** - * @type int - */ - public $default_port = 119; - - /** - * @type bool - */ - public $browsable = false; - - /** - * @param HTMLPurifier_URI $uri - * @param HTMLPurifier_Config $config - * @param HTMLPurifier_Context $context - * @return bool - */ - public function doValidate(&$uri, $config, $context) - { - $uri->userinfo = null; - $uri->query = null; - return true; - } -} - - - - - -/** - * Performs safe variable parsing based on types which can be used by - * users. This may not be able to represent all possible data inputs, - * however. - */ -class HTMLPurifier_VarParser_Flexible extends HTMLPurifier_VarParser -{ - /** - * @param mixed $var - * @param int $type - * @param bool $allow_null - * @return array|bool|float|int|mixed|null|string - * @throws HTMLPurifier_VarParserException - */ - protected function parseImplementation($var, $type, $allow_null) - { - if ($allow_null && $var === null) { - return null; - } - switch ($type) { - // Note: if code "breaks" from the switch, it triggers a generic - // exception to be thrown. Specific errors can be specifically - // done here. - case self::MIXED: - case self::ISTRING: - case self::STRING: - case self::TEXT: - case self::ITEXT: - return $var; - case self::INT: - if (is_string($var) && ctype_digit($var)) { - $var = (int)$var; - } - return $var; - case self::FLOAT: - if ((is_string($var) && is_numeric($var)) || is_int($var)) { - $var = (float)$var; - } - return $var; - case self::BOOL: - if (is_int($var) && ($var === 0 || $var === 1)) { - $var = (bool)$var; - } elseif (is_string($var)) { - if ($var == 'on' || $var == 'true' || $var == '1') { - $var = true; - } elseif ($var == 'off' || $var == 'false' || $var == '0') { - $var = false; - } else { - throw new HTMLPurifier_VarParserException("Unrecognized value '$var' for $type"); - } - } - return $var; - case self::ALIST: - case self::HASH: - case self::LOOKUP: - if (is_string($var)) { - // special case: technically, this is an array with - // a single empty string item, but having an empty - // array is more intuitive - if ($var == '') { - return array(); - } - if (strpos($var, "\n") === false && strpos($var, "\r") === false) { - // simplistic string to array method that only works - // for simple lists of tag names or alphanumeric characters - $var = explode(',', $var); - } else { - $var = preg_split('/(,|[\n\r]+)/', $var); - } - // remove spaces - foreach ($var as $i => $j) { - $var[$i] = trim($j); - } - if ($type === self::HASH) { - // key:value,key2:value2 - $nvar = array(); - foreach ($var as $keypair) { - $c = explode(':', $keypair, 2); - if (!isset($c[1])) { - continue; - } - $nvar[trim($c[0])] = trim($c[1]); - } - $var = $nvar; - } - } - if (!is_array($var)) { - break; - } - $keys = array_keys($var); - if ($keys === array_keys($keys)) { - if ($type == self::ALIST) { - return $var; - } elseif ($type == self::LOOKUP) { - $new = array(); - foreach ($var as $key) { - $new[$key] = true; - } - return $new; - } else { - break; - } - } - if ($type === self::ALIST) { - trigger_error("Array list did not have consecutive integer indexes", E_USER_WARNING); - return array_values($var); - } - if ($type === self::LOOKUP) { - foreach ($var as $key => $value) { - if ($value !== true) { - trigger_error( - "Lookup array has non-true value at key '$key'; " . - "maybe your input array was not indexed numerically", - E_USER_WARNING - ); - } - $var[$key] = true; - } - } - return $var; - default: - $this->errorInconsistent(__CLASS__, $type); - } - $this->errorGeneric($var, $type); - } -} - - - - - -/** - * This variable parser uses PHP's internal code engine. Because it does - * this, it can represent all inputs; however, it is dangerous and cannot - * be used by users. - */ -class HTMLPurifier_VarParser_Native extends HTMLPurifier_VarParser -{ - - /** - * @param mixed $var - * @param int $type - * @param bool $allow_null - * @return null|string - */ - protected function parseImplementation($var, $type, $allow_null) - { - return $this->evalExpression($var); - } - - /** - * @param string $expr - * @return mixed - * @throws HTMLPurifier_VarParserException - */ - protected function evalExpression($expr) - { - $var = null; - $result = eval("\$var = $expr;"); - if ($result === false) { - throw new HTMLPurifier_VarParserException("Fatal error in evaluated code"); - } - return $var; - } -} diff --git a/tools/htmlpurifier/HTMLPurifier/Arborize.php b/tools/htmlpurifier/HTMLPurifier/Arborize.php new file mode 100644 index 000000000..d2e9d22a2 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/Arborize.php @@ -0,0 +1,71 @@ +getHTMLDefinition(); + $parent = new HTMLPurifier_Token_Start($definition->info_parent); + $stack = array($parent->toNode()); + foreach ($tokens as $token) { + $token->skip = null; // [MUT] + $token->carryover = null; // [MUT] + if ($token instanceof HTMLPurifier_Token_End) { + $token->start = null; // [MUT] + $r = array_pop($stack); + //assert($r->name === $token->name); + //assert(empty($token->attr)); + $r->endCol = $token->col; + $r->endLine = $token->line; + $r->endArmor = $token->armor; + continue; + } + $node = $token->toNode(); + $stack[count($stack)-1]->children[] = $node; + if ($token instanceof HTMLPurifier_Token_Start) { + $stack[] = $node; + } + } + //assert(count($stack) == 1); + return $stack[0]; + } + + public static function flatten($node, $config, $context) { + $level = 0; + $nodes = array($level => new HTMLPurifier_Queue(array($node))); + $closingTokens = array(); + $tokens = array(); + do { + while (!$nodes[$level]->isEmpty()) { + $node = $nodes[$level]->shift(); // FIFO + list($start, $end) = $node->toTokenPair(); + if ($level > 0) { + $tokens[] = $start; + } + if ($end !== NULL) { + $closingTokens[$level][] = $end; + } + if ($node instanceof HTMLPurifier_Node_Element) { + $level++; + $nodes[$level] = new HTMLPurifier_Queue(); + foreach ($node->children as $childNode) { + $nodes[$level]->push($childNode); + } + } + } + $level--; + if ($level && isset($closingTokens[$level])) { + while ($token = array_pop($closingTokens[$level])) { + $tokens[] = $token; + } + } + } while ($level > 0); + return $tokens; + } +} diff --git a/tools/htmlpurifier/HTMLPurifier/AttrCollections.php b/tools/htmlpurifier/HTMLPurifier/AttrCollections.php new file mode 100644 index 000000000..c7b17cf14 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrCollections.php @@ -0,0 +1,148 @@ +doConstruct($attr_types, $modules); + } + + public function doConstruct($attr_types, $modules) + { + // load extensions from the modules + foreach ($modules as $module) { + foreach ($module->attr_collections as $coll_i => $coll) { + if (!isset($this->info[$coll_i])) { + $this->info[$coll_i] = array(); + } + foreach ($coll as $attr_i => $attr) { + if ($attr_i === 0 && isset($this->info[$coll_i][$attr_i])) { + // merge in includes + $this->info[$coll_i][$attr_i] = array_merge( + $this->info[$coll_i][$attr_i], + $attr + ); + continue; + } + $this->info[$coll_i][$attr_i] = $attr; + } + } + } + // perform internal expansions and inclusions + foreach ($this->info as $name => $attr) { + // merge attribute collections that include others + $this->performInclusions($this->info[$name]); + // replace string identifiers with actual attribute objects + $this->expandIdentifiers($this->info[$name], $attr_types); + } + } + + /** + * Takes a reference to an attribute associative array and performs + * all inclusions specified by the zero index. + * @param array &$attr Reference to attribute array + */ + public function performInclusions(&$attr) + { + if (!isset($attr[0])) { + return; + } + $merge = $attr[0]; + $seen = array(); // recursion guard + // loop through all the inclusions + for ($i = 0; isset($merge[$i]); $i++) { + if (isset($seen[$merge[$i]])) { + continue; + } + $seen[$merge[$i]] = true; + // foreach attribute of the inclusion, copy it over + if (!isset($this->info[$merge[$i]])) { + continue; + } + foreach ($this->info[$merge[$i]] as $key => $value) { + if (isset($attr[$key])) { + continue; + } // also catches more inclusions + $attr[$key] = $value; + } + if (isset($this->info[$merge[$i]][0])) { + // recursion + $merge = array_merge($merge, $this->info[$merge[$i]][0]); + } + } + unset($attr[0]); + } + + /** + * Expands all string identifiers in an attribute array by replacing + * them with the appropriate values inside HTMLPurifier_AttrTypes + * @param array &$attr Reference to attribute array + * @param HTMLPurifier_AttrTypes $attr_types HTMLPurifier_AttrTypes instance + */ + public function expandIdentifiers(&$attr, $attr_types) + { + // because foreach will process new elements we add, make sure we + // skip duplicates + $processed = array(); + + foreach ($attr as $def_i => $def) { + // skip inclusions + if ($def_i === 0) { + continue; + } + + if (isset($processed[$def_i])) { + continue; + } + + // determine whether or not attribute is required + if ($required = (strpos($def_i, '*') !== false)) { + // rename the definition + unset($attr[$def_i]); + $def_i = trim($def_i, '*'); + $attr[$def_i] = $def; + } + + $processed[$def_i] = true; + + // if we've already got a literal object, move on + if (is_object($def)) { + // preserve previous required + $attr[$def_i]->required = ($required || $attr[$def_i]->required); + continue; + } + + if ($def === false) { + unset($attr[$def_i]); + continue; + } + + if ($t = $attr_types->get($def)) { + $attr[$def_i] = $t; + $attr[$def_i]->required = $required; + } else { + unset($attr[$def_i]); + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef.php b/tools/htmlpurifier/HTMLPurifier/AttrDef.php new file mode 100644 index 000000000..739646fa7 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef.php @@ -0,0 +1,144 @@ + by removing + * leading and trailing whitespace, ignoring line feeds, and replacing + * carriage returns and tabs with spaces. While most useful for HTML + * attributes specified as CDATA, it can also be applied to most CSS + * values. + * + * @note This method is not entirely standards compliant, as trim() removes + * more types of whitespace than specified in the spec. In practice, + * this is rarely a problem, as those extra characters usually have + * already been removed by HTMLPurifier_Encoder. + * + * @warning This processing is inconsistent with XML's whitespace handling + * as specified by section 3.3.3 and referenced XHTML 1.0 section + * 4.7. However, note that we are NOT necessarily + * parsing XML, thus, this behavior may still be correct. We + * assume that newlines have been normalized. + */ + public function parseCDATA($string) + { + $string = trim($string); + $string = str_replace(array("\n", "\t", "\r"), ' ', $string); + return $string; + } + + /** + * Factory method for creating this class from a string. + * @param string $string String construction info + * @return HTMLPurifier_AttrDef Created AttrDef object corresponding to $string + */ + public function make($string) + { + // default implementation, return a flyweight of this object. + // If $string has an effect on the returned object (i.e. you + // need to overload this method), it is best + // to clone or instantiate new copies. (Instantiation is safer.) + return $this; + } + + /** + * Removes spaces from rgb(0, 0, 0) so that shorthand CSS properties work + * properly. THIS IS A HACK! + * @param string $string a CSS colour definition + * @return string + */ + protected function mungeRgb($string) + { + $p = '\s*(\d+(\.\d+)?([%]?))\s*'; + + if (preg_match('/(rgba|hsla)\(/', $string)) { + return preg_replace('/(rgba|hsla)\('.$p.','.$p.','.$p.','.$p.'\)/', '\1(\2,\5,\8,\11)', $string); + } + + return preg_replace('/(rgb|hsl)\('.$p.','.$p.','.$p.'\)/', '\1(\2,\5,\8)', $string); + } + + /** + * Parses a possibly escaped CSS string and returns the "pure" + * version of it. + */ + protected function expandCSSEscape($string) + { + // flexibly parse it + $ret = ''; + for ($i = 0, $c = strlen($string); $i < $c; $i++) { + if ($string[$i] === '\\') { + $i++; + if ($i >= $c) { + $ret .= '\\'; + break; + } + if (ctype_xdigit($string[$i])) { + $code = $string[$i]; + for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) { + if (!ctype_xdigit($string[$i])) { + break; + } + $code .= $string[$i]; + } + // We have to be extremely careful when adding + // new characters, to make sure we're not breaking + // the encoding. + $char = HTMLPurifier_Encoder::unichr(hexdec($code)); + if (HTMLPurifier_Encoder::cleanUTF8($char) === '') { + continue; + } + $ret .= $char; + if ($i < $c && trim($string[$i]) !== '') { + $i--; + } + continue; + } + if ($string[$i] === "\n") { + continue; + } + } + $ret .= $string[$i]; + } + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS.php new file mode 100644 index 000000000..ad2cb90ad --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS.php @@ -0,0 +1,136 @@ +parseCDATA($css); + + $definition = $config->getCSSDefinition(); + $allow_duplicates = $config->get("CSS.AllowDuplicates"); + + + // According to the CSS2.1 spec, the places where a + // non-delimiting semicolon can appear are in strings + // escape sequences. So here is some dumb hack to + // handle quotes. + $len = strlen($css); + $accum = ""; + $declarations = array(); + $quoted = false; + for ($i = 0; $i < $len; $i++) { + $c = strcspn($css, ";'\"", $i); + $accum .= substr($css, $i, $c); + $i += $c; + if ($i == $len) break; + $d = $css[$i]; + if ($quoted) { + $accum .= $d; + if ($d == $quoted) { + $quoted = false; + } + } else { + if ($d == ";") { + $declarations[] = $accum; + $accum = ""; + } else { + $accum .= $d; + $quoted = $d; + } + } + } + if ($accum != "") $declarations[] = $accum; + + $propvalues = array(); + $new_declarations = ''; + + /** + * Name of the current CSS property being validated. + */ + $property = false; + $context->register('CurrentCSSProperty', $property); + + foreach ($declarations as $declaration) { + if (!$declaration) { + continue; + } + if (!strpos($declaration, ':')) { + continue; + } + list($property, $value) = explode(':', $declaration, 2); + $property = trim($property); + $value = trim($value); + $ok = false; + do { + if (isset($definition->info[$property])) { + $ok = true; + break; + } + if (ctype_lower($property)) { + break; + } + $property = strtolower($property); + if (isset($definition->info[$property])) { + $ok = true; + break; + } + } while (0); + if (!$ok) { + continue; + } + // inefficient call, since the validator will do this again + if (strtolower(trim($value)) !== 'inherit') { + // inherit works for everything (but only on the base property) + $result = $definition->info[$property]->validate( + $value, + $config, + $context + ); + } else { + $result = 'inherit'; + } + if ($result === false) { + continue; + } + if ($allow_duplicates) { + $new_declarations .= "$property:$result;"; + } else { + $propvalues[$property] = $result; + } + } + + $context->destroy('CurrentCSSProperty'); + + // procedure does not write the new CSS simultaneously, so it's + // slightly inefficient, but it's the only way of getting rid of + // duplicates. Perhaps config to optimize it, but not now. + + foreach ($propvalues as $prop => $value) { + $new_declarations .= "$prop:$value;"; + } + + return $new_declarations ? $new_declarations : false; + + } + +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/AlphaValue.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/AlphaValue.php new file mode 100644 index 000000000..af2b83dff --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/AlphaValue.php @@ -0,0 +1,34 @@ + 1.0) { + $result = '1'; + } + return $result; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Background.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Background.php new file mode 100644 index 000000000..7f1ea3b0f --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Background.php @@ -0,0 +1,111 @@ +getCSSDefinition(); + $this->info['background-color'] = $def->info['background-color']; + $this->info['background-image'] = $def->info['background-image']; + $this->info['background-repeat'] = $def->info['background-repeat']; + $this->info['background-attachment'] = $def->info['background-attachment']; + $this->info['background-position'] = $def->info['background-position']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + // regular pre-processing + $string = $this->parseCDATA($string); + if ($string === '') { + return false; + } + + // munge rgb() decl if necessary + $string = $this->mungeRgb($string); + + // assumes URI doesn't have spaces in it + $bits = explode(' ', $string); // bits to process + + $caught = array(); + $caught['color'] = false; + $caught['image'] = false; + $caught['repeat'] = false; + $caught['attachment'] = false; + $caught['position'] = false; + + $i = 0; // number of catches + + foreach ($bits as $bit) { + if ($bit === '') { + continue; + } + foreach ($caught as $key => $status) { + if ($key != 'position') { + if ($status !== false) { + continue; + } + $r = $this->info['background-' . $key]->validate($bit, $config, $context); + } else { + $r = $bit; + } + if ($r === false) { + continue; + } + if ($key == 'position') { + if ($caught[$key] === false) { + $caught[$key] = ''; + } + $caught[$key] .= $r . ' '; + } else { + $caught[$key] = $r; + } + $i++; + break; + } + } + + if (!$i) { + return false; + } + if ($caught['position'] !== false) { + $caught['position'] = $this->info['background-position']-> + validate($caught['position'], $config, $context); + } + + $ret = array(); + foreach ($caught as $value) { + if ($value === false) { + continue; + } + $ret[] = $value; + } + + if (empty($ret)) { + return false; + } + return implode(' ', $ret); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php new file mode 100644 index 000000000..4580ef5a9 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php @@ -0,0 +1,157 @@ + | | left | center | right + ] + [ + | | top | center | bottom + ]? + ] | + [ // this signifies that the vertical and horizontal adjectives + // can be arbitrarily ordered, however, there can only be two, + // one of each, or none at all + [ + left | center | right + ] || + [ + top | center | bottom + ] + ] + top, left = 0% + center, (none) = 50% + bottom, right = 100% +*/ + +/* QuirksMode says: + keyword + length/percentage must be ordered correctly, as per W3C + + Internet Explorer and Opera, however, support arbitrary ordering. We + should fix it up. + + Minor issue though, not strictly necessary. +*/ + +// control freaks may appreciate the ability to convert these to +// percentages or something, but it's not necessary + +/** + * Validates the value of background-position. + */ +class HTMLPurifier_AttrDef_CSS_BackgroundPosition extends HTMLPurifier_AttrDef +{ + + /** + * @type HTMLPurifier_AttrDef_CSS_Length + */ + protected $length; + + /** + * @type HTMLPurifier_AttrDef_CSS_Percentage + */ + protected $percentage; + + public function __construct() + { + $this->length = new HTMLPurifier_AttrDef_CSS_Length(); + $this->percentage = new HTMLPurifier_AttrDef_CSS_Percentage(); + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + $bits = explode(' ', $string); + + $keywords = array(); + $keywords['h'] = false; // left, right + $keywords['v'] = false; // top, bottom + $keywords['ch'] = false; // center (first word) + $keywords['cv'] = false; // center (second word) + $measures = array(); + + $i = 0; + + $lookup = array( + 'top' => 'v', + 'bottom' => 'v', + 'left' => 'h', + 'right' => 'h', + 'center' => 'c' + ); + + foreach ($bits as $bit) { + if ($bit === '') { + continue; + } + + // test for keyword + $lbit = ctype_lower($bit) ? $bit : strtolower($bit); + if (isset($lookup[$lbit])) { + $status = $lookup[$lbit]; + if ($status == 'c') { + if ($i == 0) { + $status = 'ch'; + } else { + $status = 'cv'; + } + } + $keywords[$status] = $lbit; + $i++; + } + + // test for length + $r = $this->length->validate($bit, $config, $context); + if ($r !== false) { + $measures[] = $r; + $i++; + } + + // test for percentage + $r = $this->percentage->validate($bit, $config, $context); + if ($r !== false) { + $measures[] = $r; + $i++; + } + } + + if (!$i) { + return false; + } // no valid values were caught + + $ret = array(); + + // first keyword + if ($keywords['h']) { + $ret[] = $keywords['h']; + } elseif ($keywords['ch']) { + $ret[] = $keywords['ch']; + $keywords['cv'] = false; // prevent re-use: center = center center + } elseif (count($measures)) { + $ret[] = array_shift($measures); + } + + if ($keywords['v']) { + $ret[] = $keywords['v']; + } elseif ($keywords['cv']) { + $ret[] = $keywords['cv']; + } elseif (count($measures)) { + $ret[] = array_shift($measures); + } + + if (empty($ret)) { + return false; + } + return implode(' ', $ret); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Border.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Border.php new file mode 100644 index 000000000..16243ba1e --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Border.php @@ -0,0 +1,56 @@ +getCSSDefinition(); + $this->info['border-width'] = $def->info['border-width']; + $this->info['border-style'] = $def->info['border-style']; + $this->info['border-top-color'] = $def->info['border-top-color']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + $string = $this->mungeRgb($string); + $bits = explode(' ', $string); + $done = array(); // segments we've finished + $ret = ''; // return value + foreach ($bits as $bit) { + foreach ($this->info as $propname => $validator) { + if (isset($done[$propname])) { + continue; + } + $r = $validator->validate($bit, $config, $context); + if ($r !== false) { + $ret .= $r . ' '; + $done[$propname] = true; + break; + } + } + } + return rtrim($ret); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Color.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Color.php new file mode 100644 index 000000000..d7287a00c --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Color.php @@ -0,0 +1,161 @@ +alpha = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + } + + /** + * @param string $color + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($color, $config, $context) + { + static $colors = null; + if ($colors === null) { + $colors = $config->get('Core.ColorKeywords'); + } + + $color = trim($color); + if ($color === '') { + return false; + } + + $lower = strtolower($color); + if (isset($colors[$lower])) { + return $colors[$lower]; + } + + if (preg_match('#(rgb|rgba|hsl|hsla)\(#', $color, $matches) === 1) { + $length = strlen($color); + if (strpos($color, ')') !== $length - 1) { + return false; + } + + // get used function : rgb, rgba, hsl or hsla + $function = $matches[1]; + + $parameters_size = 3; + $alpha_channel = false; + if (substr($function, -1) === 'a') { + $parameters_size = 4; + $alpha_channel = true; + } + + /* + * Allowed types for values : + * parameter_position => [type => max_value] + */ + $allowed_types = array( + 1 => array('percentage' => 100, 'integer' => 255), + 2 => array('percentage' => 100, 'integer' => 255), + 3 => array('percentage' => 100, 'integer' => 255), + ); + $allow_different_types = false; + + if (strpos($function, 'hsl') !== false) { + $allowed_types = array( + 1 => array('integer' => 360), + 2 => array('percentage' => 100), + 3 => array('percentage' => 100), + ); + $allow_different_types = true; + } + + $values = trim(str_replace($function, '', $color), ' ()'); + + $parts = explode(',', $values); + if (count($parts) !== $parameters_size) { + return false; + } + + $type = false; + $new_parts = array(); + $i = 0; + + foreach ($parts as $part) { + $i++; + $part = trim($part); + + if ($part === '') { + return false; + } + + // different check for alpha channel + if ($alpha_channel === true && $i === count($parts)) { + $result = $this->alpha->validate($part, $config, $context); + + if ($result === false) { + return false; + } + + $new_parts[] = (string)$result; + continue; + } + + if (substr($part, -1) === '%') { + $current_type = 'percentage'; + } else { + $current_type = 'integer'; + } + + if (!array_key_exists($current_type, $allowed_types[$i])) { + return false; + } + + if (!$type) { + $type = $current_type; + } + + if ($allow_different_types === false && $type != $current_type) { + return false; + } + + $max_value = $allowed_types[$i][$current_type]; + + if ($current_type == 'integer') { + // Return value between range 0 -> $max_value + $new_parts[] = (int)max(min($part, $max_value), 0); + } elseif ($current_type == 'percentage') { + $new_parts[] = (float)max(min(rtrim($part, '%'), $max_value), 0) . '%'; + } + } + + $new_values = implode(',', $new_parts); + + $color = $function . '(' . $new_values . ')'; + } else { + // hexadecimal handling + if ($color[0] === '#') { + $hex = substr($color, 1); + } else { + $hex = $color; + $color = '#' . $color; + } + $length = strlen($hex); + if ($length !== 3 && $length !== 6) { + return false; + } + if (!ctype_xdigit($hex)) { + return false; + } + } + return $color; + } + +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Composite.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Composite.php new file mode 100644 index 000000000..9c1750554 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Composite.php @@ -0,0 +1,48 @@ +defs = $defs; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + foreach ($this->defs as $i => $def) { + $result = $this->defs[$i]->validate($string, $config, $context); + if ($result !== false) { + return $result; + } + } + return false; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php new file mode 100644 index 000000000..9d77cc9aa --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php @@ -0,0 +1,44 @@ +def = $def; + $this->element = $element; + } + + /** + * Checks if CurrentToken is set and equal to $this->element + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $token = $context->get('CurrentToken', true); + if ($token && $token->name == $this->element) { + return false; + } + return $this->def->validate($string, $config, $context); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Filter.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Filter.php new file mode 100644 index 000000000..bde4c3301 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Filter.php @@ -0,0 +1,77 @@ +intValidator = new HTMLPurifier_AttrDef_Integer(); + } + + /** + * @param string $value + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($value, $config, $context) + { + $value = $this->parseCDATA($value); + if ($value === 'none') { + return $value; + } + // if we looped this we could support multiple filters + $function_length = strcspn($value, '('); + $function = trim(substr($value, 0, $function_length)); + if ($function !== 'alpha' && + $function !== 'Alpha' && + $function !== 'progid:DXImageTransform.Microsoft.Alpha' + ) { + return false; + } + $cursor = $function_length + 1; + $parameters_length = strcspn($value, ')', $cursor); + $parameters = substr($value, $cursor, $parameters_length); + $params = explode(',', $parameters); + $ret_params = array(); + $lookup = array(); + foreach ($params as $param) { + list($key, $value) = explode('=', $param); + $key = trim($key); + $value = trim($value); + if (isset($lookup[$key])) { + continue; + } + if ($key !== 'opacity') { + continue; + } + $value = $this->intValidator->validate($value, $config, $context); + if ($value === false) { + continue; + } + $int = (int)$value; + if ($int > 100) { + $value = '100'; + } + if ($int < 0) { + $value = '0'; + } + $ret_params[] = "$key=$value"; + $lookup[$key] = true; + } + $ret_parameters = implode(',', $ret_params); + $ret_function = "$function($ret_parameters)"; + return $ret_function; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Font.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Font.php new file mode 100644 index 000000000..579b97ef1 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Font.php @@ -0,0 +1,176 @@ +getCSSDefinition(); + $this->info['font-style'] = $def->info['font-style']; + $this->info['font-variant'] = $def->info['font-variant']; + $this->info['font-weight'] = $def->info['font-weight']; + $this->info['font-size'] = $def->info['font-size']; + $this->info['line-height'] = $def->info['line-height']; + $this->info['font-family'] = $def->info['font-family']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + static $system_fonts = array( + 'caption' => true, + 'icon' => true, + 'menu' => true, + 'message-box' => true, + 'small-caption' => true, + 'status-bar' => true + ); + + // regular pre-processing + $string = $this->parseCDATA($string); + if ($string === '') { + return false; + } + + // check if it's one of the keywords + $lowercase_string = strtolower($string); + if (isset($system_fonts[$lowercase_string])) { + return $lowercase_string; + } + + $bits = explode(' ', $string); // bits to process + $stage = 0; // this indicates what we're looking for + $caught = array(); // which stage 0 properties have we caught? + $stage_1 = array('font-style', 'font-variant', 'font-weight'); + $final = ''; // output + + for ($i = 0, $size = count($bits); $i < $size; $i++) { + if ($bits[$i] === '') { + continue; + } + switch ($stage) { + case 0: // attempting to catch font-style, font-variant or font-weight + foreach ($stage_1 as $validator_name) { + if (isset($caught[$validator_name])) { + continue; + } + $r = $this->info[$validator_name]->validate( + $bits[$i], + $config, + $context + ); + if ($r !== false) { + $final .= $r . ' '; + $caught[$validator_name] = true; + break; + } + } + // all three caught, continue on + if (count($caught) >= 3) { + $stage = 1; + } + if ($r !== false) { + break; + } + case 1: // attempting to catch font-size and perhaps line-height + $found_slash = false; + if (strpos($bits[$i], '/') !== false) { + list($font_size, $line_height) = + explode('/', $bits[$i]); + if ($line_height === '') { + // ooh, there's a space after the slash! + $line_height = false; + $found_slash = true; + } + } else { + $font_size = $bits[$i]; + $line_height = false; + } + $r = $this->info['font-size']->validate( + $font_size, + $config, + $context + ); + if ($r !== false) { + $final .= $r; + // attempt to catch line-height + if ($line_height === false) { + // we need to scroll forward + for ($j = $i + 1; $j < $size; $j++) { + if ($bits[$j] === '') { + continue; + } + if ($bits[$j] === '/') { + if ($found_slash) { + return false; + } else { + $found_slash = true; + continue; + } + } + $line_height = $bits[$j]; + break; + } + } else { + // slash already found + $found_slash = true; + $j = $i; + } + if ($found_slash) { + $i = $j; + $r = $this->info['line-height']->validate( + $line_height, + $config, + $context + ); + if ($r !== false) { + $final .= '/' . $r; + } + } + $final .= ' '; + $stage = 2; + break; + } + return false; + case 2: // attempting to catch font-family + $font_family = + implode(' ', array_slice($bits, $i, $size - $i)); + $r = $this->info['font-family']->validate( + $font_family, + $config, + $context + ); + if ($r !== false) { + $final .= $r . ' '; + // processing completed successfully + return rtrim($final); + } + return false; + } + } + return false; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/FontFamily.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/FontFamily.php new file mode 100644 index 000000000..74e24c881 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/FontFamily.php @@ -0,0 +1,219 @@ +mask = '_- '; + for ($c = 'a'; $c <= 'z'; $c++) { + $this->mask .= $c; + } + for ($c = 'A'; $c <= 'Z'; $c++) { + $this->mask .= $c; + } + for ($c = '0'; $c <= '9'; $c++) { + $this->mask .= $c; + } // cast-y, but should be fine + // special bytes used by UTF-8 + for ($i = 0x80; $i <= 0xFF; $i++) { + // We don't bother excluding invalid bytes in this range, + // because the our restriction of well-formed UTF-8 will + // prevent these from ever occurring. + $this->mask .= chr($i); + } + + /* + PHP's internal strcspn implementation is + O(length of string * length of mask), making it inefficient + for large masks. However, it's still faster than + preg_match 8) + for (p = s1;;) { + spanp = s2; + do { + if (*spanp == c || p == s1_end) { + return p - s1; + } + } while (spanp++ < (s2_end - 1)); + c = *++p; + } + */ + // possible optimization: invert the mask. + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + static $generic_names = array( + 'serif' => true, + 'sans-serif' => true, + 'monospace' => true, + 'fantasy' => true, + 'cursive' => true + ); + $allowed_fonts = $config->get('CSS.AllowedFonts'); + + // assume that no font names contain commas in them + $fonts = explode(',', $string); + $final = ''; + foreach ($fonts as $font) { + $font = trim($font); + if ($font === '') { + continue; + } + // match a generic name + if (isset($generic_names[$font])) { + if ($allowed_fonts === null || isset($allowed_fonts[$font])) { + $final .= $font . ', '; + } + continue; + } + // match a quoted name + if ($font[0] === '"' || $font[0] === "'") { + $length = strlen($font); + if ($length <= 2) { + continue; + } + $quote = $font[0]; + if ($font[$length - 1] !== $quote) { + continue; + } + $font = substr($font, 1, $length - 2); + } + + $font = $this->expandCSSEscape($font); + + // $font is a pure representation of the font name + + if ($allowed_fonts !== null && !isset($allowed_fonts[$font])) { + continue; + } + + if (ctype_alnum($font) && $font !== '') { + // very simple font, allow it in unharmed + $final .= $font . ', '; + continue; + } + + // bugger out on whitespace. form feed (0C) really + // shouldn't show up regardless + $font = str_replace(array("\n", "\t", "\r", "\x0C"), ' ', $font); + + // Here, there are various classes of characters which need + // to be treated differently: + // - Alphanumeric characters are essentially safe. We + // handled these above. + // - Spaces require quoting, though most parsers will do + // the right thing if there aren't any characters that + // can be misinterpreted + // - Dashes rarely occur, but they fairly unproblematic + // for parsing/rendering purposes. + // The above characters cover the majority of Western font + // names. + // - Arbitrary Unicode characters not in ASCII. Because + // most parsers give little thought to Unicode, treatment + // of these codepoints is basically uniform, even for + // punctuation-like codepoints. These characters can + // show up in non-Western pages and are supported by most + // major browsers, for example: "MS 明朝" is a + // legitimate font-name + // . See + // the CSS3 spec for more examples: + // + // You can see live samples of these on the Internet: + // + // However, most of these fonts have ASCII equivalents: + // for example, 'MS Mincho', and it's considered + // professional to use ASCII font names instead of + // Unicode font names. Thanks Takeshi Terada for + // providing this information. + // The following characters, to my knowledge, have not been + // used to name font names. + // - Single quote. While theoretically you might find a + // font name that has a single quote in its name (serving + // as an apostrophe, e.g. Dave's Scribble), I haven't + // been able to find any actual examples of this. + // Internet Explorer's cssText translation (which I + // believe is invoked by innerHTML) normalizes any + // quoting to single quotes, and fails to escape single + // quotes. (Note that this is not IE's behavior for all + // CSS properties, just some sort of special casing for + // font-family). So a single quote *cannot* be used + // safely in the font-family context if there will be an + // innerHTML/cssText translation. Note that Firefox 3.x + // does this too. + // - Double quote. In IE, these get normalized to + // single-quotes, no matter what the encoding. (Fun + // fact, in IE8, the 'content' CSS property gained + // support, where they special cased to preserve encoded + // double quotes, but still translate unadorned double + // quotes into single quotes.) So, because their + // fixpoint behavior is identical to single quotes, they + // cannot be allowed either. Firefox 3.x displays + // single-quote style behavior. + // - Backslashes are reduced by one (so \\ -> \) every + // iteration, so they cannot be used safely. This shows + // up in IE7, IE8 and FF3 + // - Semicolons, commas and backticks are handled properly. + // - The rest of the ASCII punctuation is handled properly. + // We haven't checked what browsers do to unadorned + // versions, but this is not important as long as the + // browser doesn't /remove/ surrounding quotes (as IE does + // for HTML). + // + // With these results in hand, we conclude that there are + // various levels of safety: + // - Paranoid: alphanumeric, spaces and dashes(?) + // - International: Paranoid + non-ASCII Unicode + // - Edgy: Everything except quotes, backslashes + // - NoJS: Standards compliance, e.g. sod IE. Note that + // with some judicious character escaping (since certain + // types of escaping doesn't work) this is theoretically + // OK as long as innerHTML/cssText is not called. + // We believe that international is a reasonable default + // (that we will implement now), and once we do more + // extensive research, we may feel comfortable with dropping + // it down to edgy. + + // Edgy: alphanumeric, spaces, dashes, underscores and Unicode. Use of + // str(c)spn assumes that the string was already well formed + // Unicode (which of course it is). + if (strspn($font, $this->mask) !== strlen($font)) { + continue; + } + + // Historical: + // In the absence of innerHTML/cssText, these ugly + // transforms don't pose a security risk (as \\ and \" + // might--these escapes are not supported by most browsers). + // We could try to be clever and use single-quote wrapping + // when there is a double quote present, but I have choosen + // not to implement that. (NOTE: you can reduce the amount + // of escapes by one depending on what quoting style you use) + // $font = str_replace('\\', '\\5C ', $font); + // $font = str_replace('"', '\\22 ', $font); + // $font = str_replace("'", '\\27 ', $font); + + // font possibly with spaces, requires quoting + $final .= "'$font', "; + } + $final = rtrim($final, ', '); + if ($final === '') { + return false; + } + return $final; + } + +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Ident.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Ident.php new file mode 100644 index 000000000..973002c17 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Ident.php @@ -0,0 +1,32 @@ +def = $def; + $this->allow = $allow; + } + + /** + * Intercepts and removes !important if necessary + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + // test for ! and important tokens + $string = trim($string); + $is_important = false; + // :TODO: optimization: test directly for !important and ! important + if (strlen($string) >= 9 && substr($string, -9) === 'important') { + $temp = rtrim(substr($string, 0, -9)); + // use a temp, because we might want to restore important + if (strlen($temp) >= 1 && substr($temp, -1) === '!') { + $string = rtrim(substr($temp, 0, -1)); + $is_important = true; + } + } + $string = $this->def->validate($string, $config, $context); + if ($this->allow && $is_important) { + $string .= ' !important'; + } + return $string; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Length.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Length.php new file mode 100644 index 000000000..f12453a04 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Length.php @@ -0,0 +1,77 @@ +min = $min !== null ? HTMLPurifier_Length::make($min) : null; + $this->max = $max !== null ? HTMLPurifier_Length::make($max) : null; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + + // Optimizations + if ($string === '') { + return false; + } + if ($string === '0') { + return '0'; + } + if (strlen($string) === 1) { + return false; + } + + $length = HTMLPurifier_Length::make($string); + if (!$length->isValid()) { + return false; + } + + if ($this->min) { + $c = $length->compareTo($this->min); + if ($c === false) { + return false; + } + if ($c < 0) { + return false; + } + } + if ($this->max) { + $c = $length->compareTo($this->max); + if ($c === false) { + return false; + } + if ($c > 0) { + return false; + } + } + return $length->toString(); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/ListStyle.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/ListStyle.php new file mode 100644 index 000000000..e74d42654 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/ListStyle.php @@ -0,0 +1,112 @@ +getCSSDefinition(); + $this->info['list-style-type'] = $def->info['list-style-type']; + $this->info['list-style-position'] = $def->info['list-style-position']; + $this->info['list-style-image'] = $def->info['list-style-image']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + // regular pre-processing + $string = $this->parseCDATA($string); + if ($string === '') { + return false; + } + + // assumes URI doesn't have spaces in it + $bits = explode(' ', strtolower($string)); // bits to process + + $caught = array(); + $caught['type'] = false; + $caught['position'] = false; + $caught['image'] = false; + + $i = 0; // number of catches + $none = false; + + foreach ($bits as $bit) { + if ($i >= 3) { + return; + } // optimization bit + if ($bit === '') { + continue; + } + foreach ($caught as $key => $status) { + if ($status !== false) { + continue; + } + $r = $this->info['list-style-' . $key]->validate($bit, $config, $context); + if ($r === false) { + continue; + } + if ($r === 'none') { + if ($none) { + continue; + } else { + $none = true; + } + if ($key == 'image') { + continue; + } + } + $caught[$key] = $r; + $i++; + break; + } + } + + if (!$i) { + return false; + } + + $ret = array(); + + // construct type + if ($caught['type']) { + $ret[] = $caught['type']; + } + + // construct image + if ($caught['image']) { + $ret[] = $caught['image']; + } + + // construct position + if ($caught['position']) { + $ret[] = $caught['position']; + } + + if (empty($ret)) { + return false; + } + return implode(' ', $ret); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Multiple.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Multiple.php new file mode 100644 index 000000000..e707f871c --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Multiple.php @@ -0,0 +1,71 @@ +single = $single; + $this->max = $max; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->mungeRgb($this->parseCDATA($string)); + if ($string === '') { + return false; + } + $parts = explode(' ', $string); // parseCDATA replaced \r, \t and \n + $length = count($parts); + $final = ''; + for ($i = 0, $num = 0; $i < $length && $num < $this->max; $i++) { + if (ctype_space($parts[$i])) { + continue; + } + $result = $this->single->validate($parts[$i], $config, $context); + if ($result !== false) { + $final .= $result . ' '; + $num++; + } + } + if ($final === '') { + return false; + } + return rtrim($final); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Number.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Number.php new file mode 100644 index 000000000..ef49d20fd --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Number.php @@ -0,0 +1,90 @@ +non_negative = $non_negative; + } + + /** + * @param string $number + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string|bool + * @warning Some contexts do not pass $config, $context. These + * variables should not be used without checking HTMLPurifier_Length + */ + public function validate($number, $config, $context) + { + $number = $this->parseCDATA($number); + + if ($number === '') { + return false; + } + if ($number === '0') { + return '0'; + } + + $sign = ''; + switch ($number[0]) { + case '-': + if ($this->non_negative) { + return false; + } + $sign = '-'; + case '+': + $number = substr($number, 1); + } + + if (ctype_digit($number)) { + $number = ltrim($number, '0'); + return $number ? $sign . $number : '0'; + } + + // Period is the only non-numeric character allowed + if (strpos($number, '.') === false) { + return false; + } + + list($left, $right) = explode('.', $number, 2); + + if ($left === '' && $right === '') { + return false; + } + if ($left !== '' && !ctype_digit($left)) { + return false; + } + + // Remove leading zeros until positive number or a zero stays left + if (ltrim($left, '0') != '') { + $left = ltrim($left, '0'); + } else { + $left = '0'; + } + + $right = rtrim($right, '0'); + + if ($right === '') { + return $left ? $sign . $left : '0'; + } elseif (!ctype_digit($right)) { + return false; + } + return $sign . $left . '.' . $right; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Percentage.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Percentage.php new file mode 100644 index 000000000..f0f25c50a --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/Percentage.php @@ -0,0 +1,54 @@ +number_def = new HTMLPurifier_AttrDef_CSS_Number($non_negative); + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + + if ($string === '') { + return false; + } + $length = strlen($string); + if ($length === 1) { + return false; + } + if ($string[$length - 1] !== '%') { + return false; + } + + $number = substr($string, 0, $length - 1); + $number = $this->number_def->validate($number, $config, $context); + + if ($number === false) { + return false; + } + return "$number%"; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/TextDecoration.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/TextDecoration.php new file mode 100644 index 000000000..5fd4b7f7b --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/TextDecoration.php @@ -0,0 +1,46 @@ + true, + 'overline' => true, + 'underline' => true, + ); + + $string = strtolower($this->parseCDATA($string)); + + if ($string === 'none') { + return $string; + } + + $parts = explode(' ', $string); + $final = ''; + foreach ($parts as $part) { + if (isset($allowed_values[$part])) { + $final .= $part . ' '; + } + } + $final = rtrim($final); + if ($final === '') { + return false; + } + return $final; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/URI.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/URI.php new file mode 100644 index 000000000..6617acace --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/URI.php @@ -0,0 +1,77 @@ +parseCDATA($uri_string); + if (strpos($uri_string, 'url(') !== 0) { + return false; + } + $uri_string = substr($uri_string, 4); + if (strlen($uri_string) == 0) { + return false; + } + $new_length = strlen($uri_string) - 1; + if ($uri_string[$new_length] != ')') { + return false; + } + $uri = trim(substr($uri_string, 0, $new_length)); + + if (!empty($uri) && ($uri[0] == "'" || $uri[0] == '"')) { + $quote = $uri[0]; + $new_length = strlen($uri) - 1; + if ($uri[$new_length] !== $quote) { + return false; + } + $uri = substr($uri, 1, $new_length - 1); + } + + $uri = $this->expandCSSEscape($uri); + + $result = parent::validate($uri, $config, $context); + + if ($result === false) { + return false; + } + + // extra sanity check; should have been done by URI + $result = str_replace(array('"', "\\", "\n", "\x0c", "\r"), "", $result); + + // suspicious characters are ()'; we're going to percent encode + // them for safety. + $result = str_replace(array('(', ')', "'"), array('%28', '%29', '%27'), $result); + + // there's an extra bug where ampersands lose their escaping on + // an innerHTML cycle, so a very unlucky query parameter could + // then change the meaning of the URL. Unfortunately, there's + // not much we can do about that... + return "url(\"$result\")"; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/index.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/CSS/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/Clone.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/Clone.php new file mode 100644 index 000000000..6698a00c0 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/Clone.php @@ -0,0 +1,44 @@ +clone = $clone; + } + + /** + * @param string $v + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($v, $config, $context) + { + return $this->clone->validate($v, $config, $context); + } + + /** + * @param string $string + * @return HTMLPurifier_AttrDef + */ + public function make($string) + { + return clone $this->clone; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/Enum.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/Enum.php new file mode 100644 index 000000000..8abda7f6e --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/Enum.php @@ -0,0 +1,73 @@ +valid_values = array_flip($valid_values); + $this->case_sensitive = $case_sensitive; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = trim($string); + if (!$this->case_sensitive) { + // we may want to do full case-insensitive libraries + $string = ctype_lower($string) ? $string : strtolower($string); + } + $result = isset($this->valid_values[$string]); + + return $result ? $string : false; + } + + /** + * @param string $string In form of comma-delimited list of case-insensitive + * valid values. Example: "foo,bar,baz". Prepend "s:" to make + * case sensitive + * @return HTMLPurifier_AttrDef_Enum + */ + public function make($string) + { + if (strlen($string) > 2 && $string[0] == 's' && $string[1] == ':') { + $string = substr($string, 2); + $sensitive = true; + } else { + $sensitive = false; + } + $values = explode(',', $string); + return new HTMLPurifier_AttrDef_Enum($values, $sensitive); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Bool.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Bool.php new file mode 100644 index 000000000..be3bbc8dc --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Bool.php @@ -0,0 +1,48 @@ +name = $name; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + return $this->name; + } + + /** + * @param string $string Name of attribute + * @return HTMLPurifier_AttrDef_HTML_Bool + */ + public function make($string) + { + return new HTMLPurifier_AttrDef_HTML_Bool($string); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Class.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Class.php new file mode 100644 index 000000000..d5013488f --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Class.php @@ -0,0 +1,48 @@ +getDefinition('HTML')->doctype->name; + if ($name == "XHTML 1.1" || $name == "XHTML 2.0") { + return parent::split($string, $config, $context); + } else { + return preg_split('/\s+/', $string); + } + } + + /** + * @param array $tokens + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + protected function filter($tokens, $config, $context) + { + $allowed = $config->get('Attr.AllowedClasses'); + $forbidden = $config->get('Attr.ForbiddenClasses'); + $ret = array(); + foreach ($tokens as $token) { + if (($allowed === null || isset($allowed[$token])) && + !isset($forbidden[$token]) && + // We need this O(n) check because of PHP's array + // implementation that casts -0 to 0. + !in_array($token, $ret, true) + ) { + $ret[] = $token; + } + } + return $ret; + } +} diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Color.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Color.php new file mode 100644 index 000000000..946ebb782 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Color.php @@ -0,0 +1,51 @@ +get('Core.ColorKeywords'); + } + + $string = trim($string); + + if (empty($string)) { + return false; + } + $lower = strtolower($string); + if (isset($colors[$lower])) { + return $colors[$lower]; + } + if ($string[0] === '#') { + $hex = substr($string, 1); + } else { + $hex = $string; + } + + $length = strlen($hex); + if ($length !== 3 && $length !== 6) { + return false; + } + if (!ctype_xdigit($hex)) { + return false; + } + if ($length === 3) { + $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2]; + } + return "#$hex"; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/FrameTarget.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/FrameTarget.php new file mode 100644 index 000000000..d79ba12b3 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/FrameTarget.php @@ -0,0 +1,38 @@ +valid_values === false) { + $this->valid_values = $config->get('Attr.AllowedFrameTargets'); + } + return parent::validate($string, $config, $context); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/ID.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/ID.php new file mode 100644 index 000000000..4ba45610f --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/ID.php @@ -0,0 +1,113 @@ +selector = $selector; + } + + /** + * @param string $id + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($id, $config, $context) + { + if (!$this->selector && !$config->get('Attr.EnableID')) { + return false; + } + + $id = trim($id); // trim it first + + if ($id === '') { + return false; + } + + $prefix = $config->get('Attr.IDPrefix'); + if ($prefix !== '') { + $prefix .= $config->get('Attr.IDPrefixLocal'); + // prevent re-appending the prefix + if (strpos($id, $prefix) !== 0) { + $id = $prefix . $id; + } + } elseif ($config->get('Attr.IDPrefixLocal') !== '') { + trigger_error( + '%Attr.IDPrefixLocal cannot be used unless ' . + '%Attr.IDPrefix is set', + E_USER_WARNING + ); + } + + if (!$this->selector) { + $id_accumulator =& $context->get('IDAccumulator'); + if (isset($id_accumulator->ids[$id])) { + return false; + } + } + + // we purposely avoid using regex, hopefully this is faster + + if ($config->get('Attr.ID.HTML5') === true) { + if (preg_match('/[\t\n\x0b\x0c ]/', $id)) { + return false; + } + } else { + if (ctype_alpha($id)) { + // OK + } else { + if (!ctype_alpha(@$id[0])) { + return false; + } + // primitive style of regexps, I suppose + $trim = trim( + $id, + 'A..Za..z0..9:-._' + ); + if ($trim !== '') { + return false; + } + } + } + + $regexp = $config->get('Attr.IDBlacklistRegexp'); + if ($regexp && preg_match($regexp, $id)) { + return false; + } + + if (!$this->selector) { + $id_accumulator->add($id); + } + + // if no change was made to the ID, return the result + // else, return the new id if stripping whitespace made it + // valid, or return false. + return $id; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Length.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Length.php new file mode 100644 index 000000000..1c4006fbb --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Length.php @@ -0,0 +1,56 @@ + 100) { + return '100%'; + } + return ((string)$points) . '%'; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/LinkTypes.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/LinkTypes.php new file mode 100644 index 000000000..63fa04c15 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/LinkTypes.php @@ -0,0 +1,72 @@ + 'AllowedRel', + 'rev' => 'AllowedRev' + ); + if (!isset($configLookup[$name])) { + trigger_error( + 'Unrecognized attribute name for link ' . + 'relationship.', + E_USER_ERROR + ); + return; + } + $this->name = $configLookup[$name]; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $allowed = $config->get('Attr.' . $this->name); + if (empty($allowed)) { + return false; + } + + $string = $this->parseCDATA($string); + $parts = explode(' ', $string); + + // lookup to prevent duplicates + $ret_lookup = array(); + foreach ($parts as $part) { + $part = strtolower(trim($part)); + if (!isset($allowed[$part])) { + continue; + } + $ret_lookup[$part] = true; + } + + if (empty($ret_lookup)) { + return false; + } + $string = implode(' ', array_keys($ret_lookup)); + return $string; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/MultiLength.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/MultiLength.php new file mode 100644 index 000000000..bbb20f2f8 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/MultiLength.php @@ -0,0 +1,60 @@ +split($string, $config, $context); + $tokens = $this->filter($tokens, $config, $context); + if (empty($tokens)) { + return false; + } + return implode(' ', $tokens); + } + + /** + * Splits a space separated list of tokens into its constituent parts. + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + protected function split($string, $config, $context) + { + // OPTIMIZABLE! + // do the preg_match, capture all subpatterns for reformulation + + // we don't support U+00A1 and up codepoints or + // escaping because I don't know how to do that with regexps + // and plus it would complicate optimization efforts (you never + // see that anyway). + $pattern = '/(?:(?<=\s)|\A)' . // look behind for space or string start + '((?:--|-?[A-Za-z_])[A-Za-z_\-0-9]*)' . + '(?:(?=\s)|\z)/'; // look ahead for space or string end + preg_match_all($pattern, $string, $matches); + return $matches[1]; + } + + /** + * Template method for removing certain tokens based on arbitrary criteria. + * @note If we wanted to be really functional, we'd do an array_filter + * with a callback. But... we're not. + * @param array $tokens + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + protected function filter($tokens, $config, $context) + { + return $tokens; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Pixels.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Pixels.php new file mode 100644 index 000000000..a1d019e09 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/Pixels.php @@ -0,0 +1,76 @@ +max = $max; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = trim($string); + if ($string === '0') { + return $string; + } + if ($string === '') { + return false; + } + $length = strlen($string); + if (substr($string, $length - 2) == 'px') { + $string = substr($string, 0, $length - 2); + } + if (!is_numeric($string)) { + return false; + } + $int = (int)$string; + + if ($int < 0) { + return '0'; + } + + // upper-bound value, extremely high values can + // crash operating systems, see + // WARNING, above link WILL crash you if you're using Windows + + if ($this->max !== null && $int > $this->max) { + return (string)$this->max; + } + return (string)$int; + } + + /** + * @param string $string + * @return HTMLPurifier_AttrDef + */ + public function make($string) + { + if ($string === '') { + $max = null; + } else { + $max = (int)$string; + } + $class = get_class($this); + return new $class($max); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/index.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/HTML/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/Integer.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/Integer.php new file mode 100644 index 000000000..400e707d2 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/Integer.php @@ -0,0 +1,91 @@ +negative = $negative; + $this->zero = $zero; + $this->positive = $positive; + } + + /** + * @param string $integer + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($integer, $config, $context) + { + $integer = $this->parseCDATA($integer); + if ($integer === '') { + return false; + } + + // we could possibly simply typecast it to integer, but there are + // certain fringe cases that must not return an integer. + + // clip leading sign + if ($this->negative && $integer[0] === '-') { + $digits = substr($integer, 1); + if ($digits === '0') { + $integer = '0'; + } // rm minus sign for zero + } elseif ($this->positive && $integer[0] === '+') { + $digits = $integer = substr($integer, 1); // rm unnecessary plus + } else { + $digits = $integer; + } + + // test if it's numeric + if (!ctype_digit($digits)) { + return false; + } + + // perform scope tests + if (!$this->zero && $integer == 0) { + return false; + } + if (!$this->positive && $integer > 0) { + return false; + } + if (!$this->negative && $integer < 0) { + return false; + } + + return $integer; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/Lang.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/Lang.php new file mode 100644 index 000000000..2a55cea64 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/Lang.php @@ -0,0 +1,86 @@ + 8 || !ctype_alnum($subtags[1])) { + return $new_string; + } + if (!ctype_lower($subtags[1])) { + $subtags[1] = strtolower($subtags[1]); + } + + $new_string .= '-' . $subtags[1]; + if ($num_subtags == 2) { + return $new_string; + } + + // process all other subtags, index 2 and up + for ($i = 2; $i < $num_subtags; $i++) { + $length = strlen($subtags[$i]); + if ($length == 0 || $length > 8 || !ctype_alnum($subtags[$i])) { + return $new_string; + } + if (!ctype_lower($subtags[$i])) { + $subtags[$i] = strtolower($subtags[$i]); + } + $new_string .= '-' . $subtags[$i]; + } + return $new_string; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/Switch.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/Switch.php new file mode 100644 index 000000000..c7eb3199a --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/Switch.php @@ -0,0 +1,53 @@ +tag = $tag; + $this->withTag = $with_tag; + $this->withoutTag = $without_tag; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $token = $context->get('CurrentToken', true); + if (!$token || $token->name !== $this->tag) { + return $this->withoutTag->validate($string, $config, $context); + } else { + return $this->withTag->validate($string, $config, $context); + } + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/Text.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/Text.php new file mode 100644 index 000000000..4553a4ea9 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/Text.php @@ -0,0 +1,21 @@ +parseCDATA($string); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/URI.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI.php new file mode 100644 index 000000000..c1cd89772 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI.php @@ -0,0 +1,111 @@ +parser = new HTMLPurifier_URIParser(); + $this->embedsResource = (bool)$embeds_resource; + } + + /** + * @param string $string + * @return HTMLPurifier_AttrDef_URI + */ + public function make($string) + { + $embeds = ($string === 'embedded'); + return new HTMLPurifier_AttrDef_URI($embeds); + } + + /** + * @param string $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($uri, $config, $context) + { + if ($config->get('URI.Disable')) { + return false; + } + + $uri = $this->parseCDATA($uri); + + // parse the URI + $uri = $this->parser->parse($uri); + if ($uri === false) { + return false; + } + + // add embedded flag to context for validators + $context->register('EmbeddedURI', $this->embedsResource); + + $ok = false; + do { + + // generic validation + $result = $uri->validate($config, $context); + if (!$result) { + break; + } + + // chained filtering + $uri_def = $config->getDefinition('URI'); + $result = $uri_def->filter($uri, $config, $context); + if (!$result) { + break; + } + + // scheme-specific validation + $scheme_obj = $uri->getSchemeObj($config, $context); + if (!$scheme_obj) { + break; + } + if ($this->embedsResource && !$scheme_obj->browsable) { + break; + } + $result = $scheme_obj->validate($uri, $config, $context); + if (!$result) { + break; + } + + // Post chained filtering + $result = $uri_def->postFilter($uri, $config, $context); + if (!$result) { + break; + } + + // survived gauntlet + $ok = true; + + } while (false); + + $context->destroy('EmbeddedURI'); + if (!$ok) { + return false; + } + // back to string + return $uri->toString(); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/Email.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/Email.php new file mode 100644 index 000000000..daf32b764 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/Email.php @@ -0,0 +1,20 @@ +" + // that needs more percent encoding to be done + if ($string == '') { + return false; + } + $string = trim($string); + $result = preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $string); + return $result ? $string : false; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/Host.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/Host.php new file mode 100644 index 000000000..1beeaa5d2 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/Host.php @@ -0,0 +1,142 @@ +ipv4 = new HTMLPurifier_AttrDef_URI_IPv4(); + $this->ipv6 = new HTMLPurifier_AttrDef_URI_IPv6(); + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $length = strlen($string); + // empty hostname is OK; it's usually semantically equivalent: + // the default host as defined by a URI scheme is used: + // + // If the URI scheme defines a default for host, then that + // default applies when the host subcomponent is undefined + // or when the registered name is empty (zero length). + if ($string === '') { + return ''; + } + if ($length > 1 && $string[0] === '[' && $string[$length - 1] === ']') { + //IPv6 + $ip = substr($string, 1, $length - 2); + $valid = $this->ipv6->validate($ip, $config, $context); + if ($valid === false) { + return false; + } + return '[' . $valid . ']'; + } + + // need to do checks on unusual encodings too + $ipv4 = $this->ipv4->validate($string, $config, $context); + if ($ipv4 !== false) { + return $ipv4; + } + + // A regular domain name. + + // This doesn't match I18N domain names, but we don't have proper IRI support, + // so force users to insert Punycode. + + // There is not a good sense in which underscores should be + // allowed, since it's technically not! (And if you go as + // far to allow everything as specified by the DNS spec... + // well, that's literally everything, modulo some space limits + // for the components and the overall name (which, by the way, + // we are NOT checking!). So we (arbitrarily) decide this: + // let's allow underscores wherever we would have allowed + // hyphens, if they are enabled. This is a pretty good match + // for browser behavior, for example, a large number of browsers + // cannot handle foo_.example.com, but foo_bar.example.com is + // fairly well supported. + $underscore = $config->get('Core.AllowHostnameUnderscore') ? '_' : ''; + + // Based off of RFC 1738, but amended so that + // as per RFC 3696, the top label need only not be all numeric. + // The productions describing this are: + $a = '[a-z]'; // alpha + $an = '[a-z0-9]'; // alphanum + $and = "[a-z0-9-$underscore]"; // alphanum | "-" + // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum + $domainlabel = "$an(?:$and*$an)?"; + // AMENDED as per RFC 3696 + // toplabel = alphanum | alphanum *( alphanum | "-" ) alphanum + // side condition: not all numeric + $toplabel = "$an(?:$and*$an)?"; + // hostname = *( domainlabel "." ) toplabel [ "." ] + if (preg_match("/^(?:$domainlabel\.)*($toplabel)\.?$/i", $string, $matches)) { + if (!ctype_digit($matches[1])) { + return $string; + } + } + + // PHP 5.3 and later support this functionality natively + if (function_exists('idn_to_ascii')) { + if (defined('IDNA_NONTRANSITIONAL_TO_ASCII') && defined('INTL_IDNA_VARIANT_UTS46')) { + $string = idn_to_ascii($string, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46); + } else { + $string = idn_to_ascii($string); + } + + // If we have Net_IDNA2 support, we can support IRIs by + // punycoding them. (This is the most portable thing to do, + // since otherwise we have to assume browsers support + } elseif ($config->get('Core.EnableIDNA')) { + $idna = new Net_IDNA2(array('encoding' => 'utf8', 'overlong' => false, 'strict' => true)); + // we need to encode each period separately + $parts = explode('.', $string); + try { + $new_parts = array(); + foreach ($parts as $part) { + $encodable = false; + for ($i = 0, $c = strlen($part); $i < $c; $i++) { + if (ord($part[$i]) > 0x7a) { + $encodable = true; + break; + } + } + if (!$encodable) { + $new_parts[] = $part; + } else { + $new_parts[] = $idna->encode($part); + } + } + $string = implode('.', $new_parts); + } catch (Exception $e) { + // XXX error reporting + } + } + // Try again + if (preg_match("/^($domainlabel\.)*$toplabel\.?$/i", $string)) { + return $string; + } + return false; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/IPv4.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/IPv4.php new file mode 100644 index 000000000..30ac16c9e --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/IPv4.php @@ -0,0 +1,45 @@ +ip4) { + $this->_loadRegex(); + } + + if (preg_match('#^' . $this->ip4 . '$#s', $aIP)) { + return $aIP; + } + return false; + } + + /** + * Lazy load function to prevent regex from being stuffed in + * cache. + */ + protected function _loadRegex() + { + $oct = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])'; // 0-255 + $this->ip4 = "(?:{$oct}\\.{$oct}\\.{$oct}\\.{$oct})"; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/IPv6.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/IPv6.php new file mode 100644 index 000000000..f243793ee --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/IPv6.php @@ -0,0 +1,89 @@ +ip4) { + $this->_loadRegex(); + } + + $original = $aIP; + + $hex = '[0-9a-fA-F]'; + $blk = '(?:' . $hex . '{1,4})'; + $pre = '(?:/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))'; // /0 - /128 + + // prefix check + if (strpos($aIP, '/') !== false) { + if (preg_match('#' . $pre . '$#s', $aIP, $find)) { + $aIP = substr($aIP, 0, 0 - strlen($find[0])); + unset($find); + } else { + return false; + } + } + + // IPv4-compatiblity check + if (preg_match('#(?<=:' . ')' . $this->ip4 . '$#s', $aIP, $find)) { + $aIP = substr($aIP, 0, 0 - strlen($find[0])); + $ip = explode('.', $find[0]); + $ip = array_map('dechex', $ip); + $aIP .= $ip[0] . $ip[1] . ':' . $ip[2] . $ip[3]; + unset($find, $ip); + } + + // compression check + $aIP = explode('::', $aIP); + $c = count($aIP); + if ($c > 2) { + return false; + } elseif ($c == 2) { + list($first, $second) = $aIP; + $first = explode(':', $first); + $second = explode(':', $second); + + if (count($first) + count($second) > 8) { + return false; + } + + while (count($first) < 8) { + array_push($first, '0'); + } + + array_splice($first, 8 - count($second), 8, $second); + $aIP = $first; + unset($first, $second); + } else { + $aIP = explode(':', $aIP[0]); + } + $c = count($aIP); + + if ($c != 8) { + return false; + } + + // All the pieces should be 16-bit hex strings. Are they? + foreach ($aIP as $piece) { + if (!preg_match('#^[0-9a-fA-F]{4}$#s', sprintf('%04s', $piece))) { + return false; + } + } + return $original; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/index.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/URI/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/HTMLPurifier/AttrDef/index.php b/tools/htmlpurifier/HTMLPurifier/AttrDef/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrDef/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform.php new file mode 100644 index 000000000..b428331f1 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform.php @@ -0,0 +1,60 @@ +confiscateAttr($attr, 'background'); + // some validation should happen here + + $this->prependCSS($attr, "background-image:url($background);"); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/BdoDir.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/BdoDir.php new file mode 100644 index 000000000..d66c04a5b --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/BdoDir.php @@ -0,0 +1,27 @@ +get('Attr.DefaultTextDir'); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/BgColor.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/BgColor.php new file mode 100644 index 000000000..0f51fd2ce --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/BgColor.php @@ -0,0 +1,28 @@ +confiscateAttr($attr, 'bgcolor'); + // some validation should happen here + + $this->prependCSS($attr, "background-color:$bgcolor;"); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/BoolToCSS.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/BoolToCSS.php new file mode 100644 index 000000000..f25cd0195 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/BoolToCSS.php @@ -0,0 +1,47 @@ +attr = $attr; + $this->css = $css; + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->attr])) { + return $attr; + } + unset($attr[$this->attr]); + $this->prependCSS($attr, $this->css); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/Border.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/Border.php new file mode 100644 index 000000000..057dc017f --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/Border.php @@ -0,0 +1,26 @@ +confiscateAttr($attr, 'border'); + // some validation should happen here + $this->prependCSS($attr, "border:{$border_width}px solid;"); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/EnumToCSS.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/EnumToCSS.php new file mode 100644 index 000000000..7ccd0e3fb --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/EnumToCSS.php @@ -0,0 +1,68 @@ +attr = $attr; + $this->enumToCSS = $enum_to_css; + $this->caseSensitive = (bool)$case_sensitive; + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->attr])) { + return $attr; + } + + $value = trim($attr[$this->attr]); + unset($attr[$this->attr]); + + if (!$this->caseSensitive) { + $value = strtolower($value); + } + + if (!isset($this->enumToCSS[$value])) { + return $attr; + } + $this->prependCSS($attr, $this->enumToCSS[$value]); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/ImgRequired.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/ImgRequired.php new file mode 100644 index 000000000..235ebb34b --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/ImgRequired.php @@ -0,0 +1,47 @@ +get('Core.RemoveInvalidImg')) { + return $attr; + } + $attr['src'] = $config->get('Attr.DefaultInvalidImage'); + $src = false; + } + + if (!isset($attr['alt'])) { + if ($src) { + $alt = $config->get('Attr.DefaultImageAlt'); + if ($alt === null) { + $attr['alt'] = basename($attr['src']); + } else { + $attr['alt'] = $alt; + } + } else { + $attr['alt'] = $config->get('Attr.DefaultInvalidImageAlt'); + } + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/ImgSpace.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/ImgSpace.php new file mode 100644 index 000000000..350b3358f --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/ImgSpace.php @@ -0,0 +1,61 @@ + array('left', 'right'), + 'vspace' => array('top', 'bottom') + ); + + /** + * @param string $attr + */ + public function __construct($attr) + { + $this->attr = $attr; + if (!isset($this->css[$attr])) { + trigger_error(htmlspecialchars($attr) . ' is not valid space attribute'); + } + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->attr])) { + return $attr; + } + + $width = $this->confiscateAttr($attr, $this->attr); + // some validation could happen here + + if (!isset($this->css[$this->attr])) { + return $attr; + } + + $style = ''; + foreach ($this->css[$this->attr] as $suffix) { + $property = "margin-$suffix"; + $style .= "$property:{$width}px;"; + } + $this->prependCSS($attr, $style); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/Input.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/Input.php new file mode 100644 index 000000000..3ab47ed8c --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/Input.php @@ -0,0 +1,56 @@ +pixels = new HTMLPurifier_AttrDef_HTML_Pixels(); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['type'])) { + $t = 'text'; + } else { + $t = strtolower($attr['type']); + } + if (isset($attr['checked']) && $t !== 'radio' && $t !== 'checkbox') { + unset($attr['checked']); + } + if (isset($attr['maxlength']) && $t !== 'text' && $t !== 'password') { + unset($attr['maxlength']); + } + if (isset($attr['size']) && $t !== 'text' && $t !== 'password') { + $result = $this->pixels->validate($attr['size'], $config, $context); + if ($result === false) { + unset($attr['size']); + } else { + $attr['size'] = $result; + } + } + if (isset($attr['src']) && $t !== 'image') { + unset($attr['src']); + } + if (!isset($attr['value']) && ($t === 'radio' || $t === 'checkbox')) { + $attr['value'] = ''; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/Lang.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/Lang.php new file mode 100644 index 000000000..5b0aff0e4 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/Lang.php @@ -0,0 +1,31 @@ +name = $name; + $this->cssName = $css_name ? $css_name : $name; + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->name])) { + return $attr; + } + $length = $this->confiscateAttr($attr, $this->name); + if (ctype_digit($length)) { + $length .= 'px'; + } + $this->prependCSS($attr, $this->cssName . ":$length;"); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/Name.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/Name.php new file mode 100644 index 000000000..63cce6837 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/Name.php @@ -0,0 +1,33 @@ +get('HTML.Attr.Name.UseCDATA')) { + return $attr; + } + if (!isset($attr['name'])) { + return $attr; + } + $id = $this->confiscateAttr($attr, 'name'); + if (isset($attr['id'])) { + return $attr; + } + $attr['id'] = $id; + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/NameSync.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/NameSync.php new file mode 100644 index 000000000..36079b786 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/NameSync.php @@ -0,0 +1,41 @@ +idDef = new HTMLPurifier_AttrDef_HTML_ID(); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['name'])) { + return $attr; + } + $name = $attr['name']; + if (isset($attr['id']) && $attr['id'] === $name) { + return $attr; + } + $result = $this->idDef->validate($name, $config, $context); + if ($result === false) { + unset($attr['name']); + } else { + $attr['name'] = $result; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/Nofollow.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/Nofollow.php new file mode 100644 index 000000000..1057ebee1 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/Nofollow.php @@ -0,0 +1,52 @@ +parser = new HTMLPurifier_URIParser(); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['href'])) { + return $attr; + } + + // XXX Kind of inefficient + $url = $this->parser->parse($attr['href']); + $scheme = $url->getSchemeObj($config, $context); + + if ($scheme->browsable && !$url->isLocal($config, $context)) { + if (isset($attr['rel'])) { + $rels = explode(' ', $attr['rel']); + if (!in_array('nofollow', $rels)) { + $rels[] = 'nofollow'; + } + $attr['rel'] = implode(' ', $rels); + } else { + $attr['rel'] = 'nofollow'; + } + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/SafeEmbed.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/SafeEmbed.php new file mode 100644 index 000000000..231c81a3f --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/SafeEmbed.php @@ -0,0 +1,25 @@ +uri = new HTMLPurifier_AttrDef_URI(true); // embedded + $this->wmode = new HTMLPurifier_AttrDef_Enum(array('window', 'opaque', 'transparent')); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + // If we add support for other objects, we'll need to alter the + // transforms. + switch ($attr['name']) { + // application/x-shockwave-flash + // Keep this synchronized with Injector/SafeObject.php + case 'allowScriptAccess': + $attr['value'] = 'never'; + break; + case 'allowNetworking': + $attr['value'] = 'internal'; + break; + case 'allowFullScreen': + if ($config->get('HTML.FlashAllowFullScreen')) { + $attr['value'] = ($attr['value'] == 'true') ? 'true' : 'false'; + } else { + $attr['value'] = 'false'; + } + break; + case 'wmode': + $attr['value'] = $this->wmode->validate($attr['value'], $config, $context); + break; + case 'movie': + case 'src': + $attr['name'] = "movie"; + $attr['value'] = $this->uri->validate($attr['value'], $config, $context); + break; + case 'flashvars': + // we're going to allow arbitrary inputs to the SWF, on + // the reasoning that it could only hack the SWF, not us. + break; + // add other cases to support other param name/value pairs + default: + $attr['name'] = $attr['value'] = null; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/ScriptRequired.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/ScriptRequired.php new file mode 100644 index 000000000..b7057bbf8 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/ScriptRequired.php @@ -0,0 +1,23 @@ + + */ +class HTMLPurifier_AttrTransform_ScriptRequired extends HTMLPurifier_AttrTransform +{ + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['type'])) { + $attr['type'] = 'text/javascript'; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/TargetBlank.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/TargetBlank.php new file mode 100644 index 000000000..dd63ea89c --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/TargetBlank.php @@ -0,0 +1,45 @@ +parser = new HTMLPurifier_URIParser(); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['href'])) { + return $attr; + } + + // XXX Kind of inefficient + $url = $this->parser->parse($attr['href']); + $scheme = $url->getSchemeObj($config, $context); + + if ($scheme->browsable && !$url->isBenign($config, $context)) { + $attr['target'] = '_blank'; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/TargetNoopener.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/TargetNoopener.php new file mode 100644 index 000000000..1db3c6c09 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/TargetNoopener.php @@ -0,0 +1,37 @@ + + */ +class HTMLPurifier_AttrTransform_Textarea extends HTMLPurifier_AttrTransform +{ + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + // Calculated from Firefox + if (!isset($attr['cols'])) { + $attr['cols'] = '22'; + } + if (!isset($attr['rows'])) { + $attr['rows'] = '3'; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTransform/index.php b/tools/htmlpurifier/HTMLPurifier/AttrTransform/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTransform/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/HTMLPurifier/AttrTypes.php b/tools/htmlpurifier/HTMLPurifier/AttrTypes.php new file mode 100644 index 000000000..3b70520b6 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrTypes.php @@ -0,0 +1,96 @@ +info['Enum'] = new HTMLPurifier_AttrDef_Enum(); + $this->info['Bool'] = new HTMLPurifier_AttrDef_HTML_Bool(); + + $this->info['CDATA'] = new HTMLPurifier_AttrDef_Text(); + $this->info['ID'] = new HTMLPurifier_AttrDef_HTML_ID(); + $this->info['Length'] = new HTMLPurifier_AttrDef_HTML_Length(); + $this->info['MultiLength'] = new HTMLPurifier_AttrDef_HTML_MultiLength(); + $this->info['NMTOKENS'] = new HTMLPurifier_AttrDef_HTML_Nmtokens(); + $this->info['Pixels'] = new HTMLPurifier_AttrDef_HTML_Pixels(); + $this->info['Text'] = new HTMLPurifier_AttrDef_Text(); + $this->info['URI'] = new HTMLPurifier_AttrDef_URI(); + $this->info['LanguageCode'] = new HTMLPurifier_AttrDef_Lang(); + $this->info['Color'] = new HTMLPurifier_AttrDef_HTML_Color(); + $this->info['IAlign'] = self::makeEnum('top,middle,bottom,left,right'); + $this->info['LAlign'] = self::makeEnum('top,bottom,left,right'); + $this->info['FrameTarget'] = new HTMLPurifier_AttrDef_HTML_FrameTarget(); + + // unimplemented aliases + $this->info['ContentType'] = new HTMLPurifier_AttrDef_Text(); + $this->info['ContentTypes'] = new HTMLPurifier_AttrDef_Text(); + $this->info['Charsets'] = new HTMLPurifier_AttrDef_Text(); + $this->info['Character'] = new HTMLPurifier_AttrDef_Text(); + + // "proprietary" types + $this->info['Class'] = new HTMLPurifier_AttrDef_HTML_Class(); + + // number is really a positive integer (one or more digits) + // FIXME: ^^ not always, see start and value of list items + $this->info['Number'] = new HTMLPurifier_AttrDef_Integer(false, false, true); + } + + private static function makeEnum($in) + { + return new HTMLPurifier_AttrDef_Clone(new HTMLPurifier_AttrDef_Enum(explode(',', $in))); + } + + /** + * Retrieves a type + * @param string $type String type name + * @return HTMLPurifier_AttrDef Object AttrDef for type + */ + public function get($type) + { + // determine if there is any extra info tacked on + if (strpos($type, '#') !== false) { + list($type, $string) = explode('#', $type, 2); + } else { + $string = ''; + } + + if (!isset($this->info[$type])) { + trigger_error('Cannot retrieve undefined attribute type ' . $type, E_USER_ERROR); + return; + } + return $this->info[$type]->make($string); + } + + /** + * Sets a new implementation for a type + * @param string $type String type name + * @param HTMLPurifier_AttrDef $impl Object AttrDef for type + */ + public function set($type, $impl) + { + $this->info[$type] = $impl; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/AttrValidator.php b/tools/htmlpurifier/HTMLPurifier/AttrValidator.php new file mode 100644 index 000000000..f97dc93ed --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/AttrValidator.php @@ -0,0 +1,178 @@ +getHTMLDefinition(); + $e =& $context->get('ErrorCollector', true); + + // initialize IDAccumulator if necessary + $ok =& $context->get('IDAccumulator', true); + if (!$ok) { + $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context); + $context->register('IDAccumulator', $id_accumulator); + } + + // initialize CurrentToken if necessary + $current_token =& $context->get('CurrentToken', true); + if (!$current_token) { + $context->register('CurrentToken', $token); + } + + if (!$token instanceof HTMLPurifier_Token_Start && + !$token instanceof HTMLPurifier_Token_Empty + ) { + return; + } + + // create alias to global definition array, see also $defs + // DEFINITION CALL + $d_defs = $definition->info_global_attr; + + // don't update token until the very end, to ensure an atomic update + $attr = $token->attr; + + // do global transformations (pre) + // nothing currently utilizes this + foreach ($definition->info_attr_transform_pre as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + // do local transformations only applicable to this element (pre) + // ex.

      to

      + foreach ($definition->info[$token->name]->attr_transform_pre as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + // create alias to this element's attribute definition array, see + // also $d_defs (global attribute definition array) + // DEFINITION CALL + $defs = $definition->info[$token->name]->attr; + + $attr_key = false; + $context->register('CurrentAttr', $attr_key); + + // iterate through all the attribute keypairs + // Watch out for name collisions: $key has previously been used + foreach ($attr as $attr_key => $value) { + + // call the definition + if (isset($defs[$attr_key])) { + // there is a local definition defined + if ($defs[$attr_key] === false) { + // We've explicitly been told not to allow this element. + // This is usually when there's a global definition + // that must be overridden. + // Theoretically speaking, we could have a + // AttrDef_DenyAll, but this is faster! + $result = false; + } else { + // validate according to the element's definition + $result = $defs[$attr_key]->validate( + $value, + $config, + $context + ); + } + } elseif (isset($d_defs[$attr_key])) { + // there is a global definition defined, validate according + // to the global definition + $result = $d_defs[$attr_key]->validate( + $value, + $config, + $context + ); + } else { + // system never heard of the attribute? DELETE! + $result = false; + } + + // put the results into effect + if ($result === false || $result === null) { + // this is a generic error message that should replaced + // with more specific ones when possible + if ($e) { + $e->send(E_ERROR, 'AttrValidator: Attribute removed'); + } + + // remove the attribute + unset($attr[$attr_key]); + } elseif (is_string($result)) { + // generally, if a substitution is happening, there + // was some sort of implicit correction going on. We'll + // delegate it to the attribute classes to say exactly what. + + // simple substitution + $attr[$attr_key] = $result; + } else { + // nothing happens + } + + // we'd also want slightly more complicated substitution + // involving an array as the return value, + // although we're not sure how colliding attributes would + // resolve (certain ones would be completely overriden, + // others would prepend themselves). + } + + $context->destroy('CurrentAttr'); + + // post transforms + + // global (error reporting untested) + foreach ($definition->info_attr_transform_post as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + // local (error reporting untested) + foreach ($definition->info[$token->name]->attr_transform_post as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + $token->attr = $attr; + + // destroy CurrentToken if we made it ourselves + if (!$current_token) { + $context->destroy('CurrentToken'); + } + + } + + +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/Bootstrap.php b/tools/htmlpurifier/HTMLPurifier/Bootstrap.php new file mode 100644 index 000000000..707122bb2 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/Bootstrap.php @@ -0,0 +1,124 @@ + +if (!defined('PHP_EOL')) { + switch (strtoupper(substr(PHP_OS, 0, 3))) { + case 'WIN': + define('PHP_EOL', "\r\n"); + break; + case 'DAR': + define('PHP_EOL', "\r"); + break; + default: + define('PHP_EOL', "\n"); + } +} + +/** + * Bootstrap class that contains meta-functionality for HTML Purifier such as + * the autoload function. + * + * @note + * This class may be used without any other files from HTML Purifier. + */ +class HTMLPurifier_Bootstrap +{ + + /** + * Autoload function for HTML Purifier + * @param string $class Class to load + * @return bool + */ + public static function autoload($class) + { + $file = HTMLPurifier_Bootstrap::getPath($class); + if (!$file) { + return false; + } + // Technically speaking, it should be ok and more efficient to + // just do 'require', but Antonio Parraga reports that with + // Zend extensions such as Zend debugger and APC, this invariant + // may be broken. Since we have efficient alternatives, pay + // the cost here and avoid the bug. + require_once HTMLPURIFIER_PREFIX . '/' . $file; + return true; + } + + /** + * Returns the path for a specific class. + * @param string $class Class path to get + * @return string + */ + public static function getPath($class) + { + if (strncmp('HTMLPurifier', $class, 12) !== 0) { + return false; + } + // Custom implementations + if (strncmp('HTMLPurifier_Language_', $class, 22) === 0) { + $code = str_replace('_', '-', substr($class, 22)); + $file = 'HTMLPurifier/Language/classes/' . $code . '.php'; + } else { + $file = str_replace('_', '/', $class) . '.php'; + } + if (!file_exists(HTMLPURIFIER_PREFIX . '/' . $file)) { + return false; + } + return $file; + } + + /** + * "Pre-registers" our autoloader on the SPL stack. + */ + public static function registerAutoload() + { + $autoload = array('HTMLPurifier_Bootstrap', 'autoload'); + if (($funcs = spl_autoload_functions()) === false) { + spl_autoload_register($autoload); + } elseif (function_exists('spl_autoload_unregister')) { + if (version_compare(PHP_VERSION, '5.3.0', '>=')) { + // prepend flag exists, no need for shenanigans + spl_autoload_register($autoload, true, true); + } else { + $buggy = version_compare(PHP_VERSION, '5.2.11', '<'); + $compat = version_compare(PHP_VERSION, '5.1.2', '<=') && + version_compare(PHP_VERSION, '5.1.0', '>='); + foreach ($funcs as $func) { + if ($buggy && is_array($func)) { + // :TRICKY: There are some compatibility issues and some + // places where we need to error out + $reflector = new ReflectionMethod($func[0], $func[1]); + if (!$reflector->isStatic()) { + throw new Exception( + 'HTML Purifier autoloader registrar is not compatible + with non-static object methods due to PHP Bug #44144; + Please do not use HTMLPurifier.autoload.php (or any + file that includes this file); instead, place the code: + spl_autoload_register(array(\'HTMLPurifier_Bootstrap\', \'autoload\')) + after your own autoloaders.' + ); + } + // Suprisingly, spl_autoload_register supports the + // Class::staticMethod callback format, although call_user_func doesn't + if ($compat) { + $func = implode('::', $func); + } + } + spl_autoload_unregister($func); + } + spl_autoload_register($autoload); + foreach ($funcs as $func) { + spl_autoload_register($func); + } + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/CSSDefinition.php b/tools/htmlpurifier/HTMLPurifier/CSSDefinition.php new file mode 100644 index 000000000..21f1a5899 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/CSSDefinition.php @@ -0,0 +1,533 @@ +info['text-align'] = new HTMLPurifier_AttrDef_Enum( + array('left', 'right', 'center', 'justify'), + false + ); + + $border_style = + $this->info['border-bottom-style'] = + $this->info['border-right-style'] = + $this->info['border-left-style'] = + $this->info['border-top-style'] = new HTMLPurifier_AttrDef_Enum( + array( + 'none', + 'hidden', + 'dotted', + 'dashed', + 'solid', + 'double', + 'groove', + 'ridge', + 'inset', + 'outset' + ), + false + ); + + $this->info['border-style'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_style); + + $this->info['clear'] = new HTMLPurifier_AttrDef_Enum( + array('none', 'left', 'right', 'both'), + false + ); + $this->info['float'] = new HTMLPurifier_AttrDef_Enum( + array('none', 'left', 'right'), + false + ); + $this->info['font-style'] = new HTMLPurifier_AttrDef_Enum( + array('normal', 'italic', 'oblique'), + false + ); + $this->info['font-variant'] = new HTMLPurifier_AttrDef_Enum( + array('normal', 'small-caps'), + false + ); + + $uri_or_none = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('none')), + new HTMLPurifier_AttrDef_CSS_URI() + ) + ); + + $this->info['list-style-position'] = new HTMLPurifier_AttrDef_Enum( + array('inside', 'outside'), + false + ); + $this->info['list-style-type'] = new HTMLPurifier_AttrDef_Enum( + array( + 'disc', + 'circle', + 'square', + 'decimal', + 'lower-roman', + 'upper-roman', + 'lower-alpha', + 'upper-alpha', + 'none' + ), + false + ); + $this->info['list-style-image'] = $uri_or_none; + + $this->info['list-style'] = new HTMLPurifier_AttrDef_CSS_ListStyle($config); + + $this->info['text-transform'] = new HTMLPurifier_AttrDef_Enum( + array('capitalize', 'uppercase', 'lowercase', 'none'), + false + ); + $this->info['color'] = new HTMLPurifier_AttrDef_CSS_Color(); + + $this->info['background-image'] = $uri_or_none; + $this->info['background-repeat'] = new HTMLPurifier_AttrDef_Enum( + array('repeat', 'repeat-x', 'repeat-y', 'no-repeat') + ); + $this->info['background-attachment'] = new HTMLPurifier_AttrDef_Enum( + array('scroll', 'fixed') + ); + $this->info['background-position'] = new HTMLPurifier_AttrDef_CSS_BackgroundPosition(); + + $border_color = + $this->info['border-top-color'] = + $this->info['border-bottom-color'] = + $this->info['border-left-color'] = + $this->info['border-right-color'] = + $this->info['background-color'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('transparent')), + new HTMLPurifier_AttrDef_CSS_Color() + ) + ); + + $this->info['background'] = new HTMLPurifier_AttrDef_CSS_Background($config); + + $this->info['border-color'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_color); + + $border_width = + $this->info['border-top-width'] = + $this->info['border-bottom-width'] = + $this->info['border-left-width'] = + $this->info['border-right-width'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('thin', 'medium', 'thick')), + new HTMLPurifier_AttrDef_CSS_Length('0') //disallow negative + ) + ); + + $this->info['border-width'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_width); + + $this->info['letter-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('normal')), + new HTMLPurifier_AttrDef_CSS_Length() + ) + ); + + $this->info['word-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('normal')), + new HTMLPurifier_AttrDef_CSS_Length() + ) + ); + + $this->info['font-size'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum( + array( + 'xx-small', + 'x-small', + 'small', + 'medium', + 'large', + 'x-large', + 'xx-large', + 'larger', + 'smaller' + ) + ), + new HTMLPurifier_AttrDef_CSS_Percentage(), + new HTMLPurifier_AttrDef_CSS_Length() + ) + ); + + $this->info['line-height'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('normal')), + new HTMLPurifier_AttrDef_CSS_Number(true), // no negatives + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true) + ) + ); + + $margin = + $this->info['margin-top'] = + $this->info['margin-bottom'] = + $this->info['margin-left'] = + $this->info['margin-right'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage(), + new HTMLPurifier_AttrDef_Enum(array('auto')) + ) + ); + + $this->info['margin'] = new HTMLPurifier_AttrDef_CSS_Multiple($margin); + + // non-negative + $padding = + $this->info['padding-top'] = + $this->info['padding-bottom'] = + $this->info['padding-left'] = + $this->info['padding-right'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true) + ) + ); + + $this->info['padding'] = new HTMLPurifier_AttrDef_CSS_Multiple($padding); + + $this->info['text-indent'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage() + ) + ); + + $trusted_wh = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true), + new HTMLPurifier_AttrDef_Enum(array('auto', 'initial', 'inherit')) + ) + ); + $trusted_min_wh = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true), + new HTMLPurifier_AttrDef_Enum(array('initial', 'inherit')) + ) + ); + $trusted_max_wh = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true), + new HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit')) + ) + ); + $max = $config->get('CSS.MaxImgLength'); + + $this->info['width'] = + $this->info['height'] = + $max === null ? + $trusted_wh : + new HTMLPurifier_AttrDef_Switch( + 'img', + // For img tags: + new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0', $max), + new HTMLPurifier_AttrDef_Enum(array('auto')) + ) + ), + // For everyone else: + $trusted_wh + ); + $this->info['min-width'] = + $this->info['min-height'] = + $max === null ? + $trusted_min_wh : + new HTMLPurifier_AttrDef_Switch( + 'img', + // For img tags: + new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0', $max), + new HTMLPurifier_AttrDef_Enum(array('initial', 'inherit')) + ) + ), + // For everyone else: + $trusted_min_wh + ); + $this->info['max-width'] = + $this->info['max-height'] = + $max === null ? + $trusted_max_wh : + new HTMLPurifier_AttrDef_Switch( + 'img', + // For img tags: + new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0', $max), + new HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit')) + ) + ), + // For everyone else: + $trusted_max_wh + ); + + $this->info['text-decoration'] = new HTMLPurifier_AttrDef_CSS_TextDecoration(); + + $this->info['font-family'] = new HTMLPurifier_AttrDef_CSS_FontFamily(); + + // this could use specialized code + $this->info['font-weight'] = new HTMLPurifier_AttrDef_Enum( + array( + 'normal', + 'bold', + 'bolder', + 'lighter', + '100', + '200', + '300', + '400', + '500', + '600', + '700', + '800', + '900' + ), + false + ); + + // MUST be called after other font properties, as it references + // a CSSDefinition object + $this->info['font'] = new HTMLPurifier_AttrDef_CSS_Font($config); + + // same here + $this->info['border'] = + $this->info['border-bottom'] = + $this->info['border-top'] = + $this->info['border-left'] = + $this->info['border-right'] = new HTMLPurifier_AttrDef_CSS_Border($config); + + $this->info['border-collapse'] = new HTMLPurifier_AttrDef_Enum( + array('collapse', 'separate') + ); + + $this->info['caption-side'] = new HTMLPurifier_AttrDef_Enum( + array('top', 'bottom') + ); + + $this->info['table-layout'] = new HTMLPurifier_AttrDef_Enum( + array('auto', 'fixed') + ); + + $this->info['vertical-align'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum( + array( + 'baseline', + 'sub', + 'super', + 'top', + 'text-top', + 'middle', + 'bottom', + 'text-bottom' + ) + ), + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage() + ) + ); + + $this->info['border-spacing'] = new HTMLPurifier_AttrDef_CSS_Multiple(new HTMLPurifier_AttrDef_CSS_Length(), 2); + + // These CSS properties don't work on many browsers, but we live + // in THE FUTURE! + $this->info['white-space'] = new HTMLPurifier_AttrDef_Enum( + array('nowrap', 'normal', 'pre', 'pre-wrap', 'pre-line') + ); + + if ($config->get('CSS.Proprietary')) { + $this->doSetupProprietary($config); + } + + if ($config->get('CSS.AllowTricky')) { + $this->doSetupTricky($config); + } + + if ($config->get('CSS.Trusted')) { + $this->doSetupTrusted($config); + } + + $allow_important = $config->get('CSS.AllowImportant'); + // wrap all attr-defs with decorator that handles !important + foreach ($this->info as $k => $v) { + $this->info[$k] = new HTMLPurifier_AttrDef_CSS_ImportantDecorator($v, $allow_important); + } + + $this->setupConfigStuff($config); + } + + /** + * @param HTMLPurifier_Config $config + */ + protected function doSetupProprietary($config) + { + // Internet Explorer only scrollbar colors + $this->info['scrollbar-arrow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-base-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-darkshadow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-face-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-highlight-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-shadow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + + // vendor specific prefixes of opacity + $this->info['-moz-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + $this->info['-khtml-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + + // only opacity, for now + $this->info['filter'] = new HTMLPurifier_AttrDef_CSS_Filter(); + + // more CSS3 + $this->info['page-break-after'] = + $this->info['page-break-before'] = new HTMLPurifier_AttrDef_Enum( + array( + 'auto', + 'always', + 'avoid', + 'left', + 'right' + ) + ); + $this->info['page-break-inside'] = new HTMLPurifier_AttrDef_Enum(array('auto', 'avoid')); + + $border_radius = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Percentage(true), // disallow negative + new HTMLPurifier_AttrDef_CSS_Length('0') // disallow negative + )); + + $this->info['border-top-left-radius'] = + $this->info['border-top-right-radius'] = + $this->info['border-bottom-right-radius'] = + $this->info['border-bottom-left-radius'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_radius, 2); + // TODO: support SLASH syntax + $this->info['border-radius'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_radius, 4); + + } + + /** + * @param HTMLPurifier_Config $config + */ + protected function doSetupTricky($config) + { + $this->info['display'] = new HTMLPurifier_AttrDef_Enum( + array( + 'inline', + 'block', + 'list-item', + 'run-in', + 'compact', + 'marker', + 'table', + 'inline-block', + 'inline-table', + 'table-row-group', + 'table-header-group', + 'table-footer-group', + 'table-row', + 'table-column-group', + 'table-column', + 'table-cell', + 'table-caption', + 'none' + ) + ); + $this->info['visibility'] = new HTMLPurifier_AttrDef_Enum( + array('visible', 'hidden', 'collapse') + ); + $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll')); + $this->info['opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + } + + /** + * @param HTMLPurifier_Config $config + */ + protected function doSetupTrusted($config) + { + $this->info['position'] = new HTMLPurifier_AttrDef_Enum( + array('static', 'relative', 'absolute', 'fixed') + ); + $this->info['top'] = + $this->info['left'] = + $this->info['right'] = + $this->info['bottom'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage(), + new HTMLPurifier_AttrDef_Enum(array('auto')), + ) + ); + $this->info['z-index'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Integer(), + new HTMLPurifier_AttrDef_Enum(array('auto')), + ) + ); + } + + /** + * Performs extra config-based processing. Based off of + * HTMLPurifier_HTMLDefinition. + * @param HTMLPurifier_Config $config + * @todo Refactor duplicate elements into common class (probably using + * composition, not inheritance). + */ + protected function setupConfigStuff($config) + { + // setup allowed elements + $support = "(for information on implementing this, see the " . + "support forums) "; + $allowed_properties = $config->get('CSS.AllowedProperties'); + if ($allowed_properties !== null) { + foreach ($this->info as $name => $d) { + if (!isset($allowed_properties[$name])) { + unset($this->info[$name]); + } + unset($allowed_properties[$name]); + } + // emit errors + foreach ($allowed_properties as $name => $d) { + // :TODO: Is this htmlspecialchars() call really necessary? + $name = htmlspecialchars($name); + trigger_error("Style attribute '$name' is not supported $support", E_USER_WARNING); + } + } + + $forbidden_properties = $config->get('CSS.ForbiddenProperties'); + if ($forbidden_properties !== null) { + foreach ($this->info as $name => $d) { + if (isset($forbidden_properties[$name])) { + unset($this->info[$name]); + } + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ChildDef.php b/tools/htmlpurifier/HTMLPurifier/ChildDef.php new file mode 100644 index 000000000..8eb17b82e --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ChildDef.php @@ -0,0 +1,52 @@ +elements; + } + + /** + * Validates nodes according to definition and returns modification. + * + * @param HTMLPurifier_Node[] $children Array of HTMLPurifier_Node + * @param HTMLPurifier_Config $config HTMLPurifier_Config object + * @param HTMLPurifier_Context $context HTMLPurifier_Context object + * @return bool|array true to leave nodes as is, false to remove parent node, array of replacement children + */ + abstract public function validateChildren($children, $config, $context); +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ChildDef/Chameleon.php b/tools/htmlpurifier/HTMLPurifier/ChildDef/Chameleon.php new file mode 100644 index 000000000..7439be26b --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ChildDef/Chameleon.php @@ -0,0 +1,67 @@ +inline = new HTMLPurifier_ChildDef_Optional($inline); + $this->block = new HTMLPurifier_ChildDef_Optional($block); + $this->elements = $this->block->elements; + } + + /** + * @param HTMLPurifier_Node[] $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function validateChildren($children, $config, $context) + { + if ($context->get('IsInline') === false) { + return $this->block->validateChildren( + $children, + $config, + $context + ); + } else { + return $this->inline->validateChildren( + $children, + $config, + $context + ); + } + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ChildDef/Custom.php b/tools/htmlpurifier/HTMLPurifier/ChildDef/Custom.php new file mode 100644 index 000000000..f515888a1 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ChildDef/Custom.php @@ -0,0 +1,102 @@ +dtd_regex = $dtd_regex; + $this->_compileRegex(); + } + + /** + * Compiles the PCRE regex from a DTD regex ($dtd_regex to $_pcre_regex) + */ + protected function _compileRegex() + { + $raw = str_replace(' ', '', $this->dtd_regex); + if ($raw[0] != '(') { + $raw = "($raw)"; + } + $el = '[#a-zA-Z0-9_.-]+'; + $reg = $raw; + + // COMPLICATED! AND MIGHT BE BUGGY! I HAVE NO CLUE WHAT I'M + // DOING! Seriously: if there's problems, please report them. + + // collect all elements into the $elements array + preg_match_all("/$el/", $reg, $matches); + foreach ($matches[0] as $match) { + $this->elements[$match] = true; + } + + // setup all elements as parentheticals with leading commas + $reg = preg_replace("/$el/", '(,\\0)', $reg); + + // remove commas when they were not solicited + $reg = preg_replace("/([^,(|]\(+),/", '\\1', $reg); + + // remove all non-paranthetical commas: they are handled by first regex + $reg = preg_replace("/,\(/", '(', $reg); + + $this->_pcre_regex = $reg; + } + + /** + * @param HTMLPurifier_Node[] $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function validateChildren($children, $config, $context) + { + $list_of_children = ''; + $nesting = 0; // depth into the nest + foreach ($children as $node) { + if (!empty($node->is_whitespace)) { + continue; + } + $list_of_children .= $node->name . ','; + } + // add leading comma to deal with stray comma declarations + $list_of_children = ',' . rtrim($list_of_children, ','); + $okay = + preg_match( + '/^,?' . $this->_pcre_regex . '$/', + $list_of_children + ); + return (bool)$okay; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ChildDef/Empty.php b/tools/htmlpurifier/HTMLPurifier/ChildDef/Empty.php new file mode 100644 index 000000000..a8a6cbdd2 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ChildDef/Empty.php @@ -0,0 +1,38 @@ + true, 'ul' => true, 'ol' => true); + + /** + * @param array $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function validateChildren($children, $config, $context) + { + // Flag for subclasses + $this->whitespace = false; + + // if there are no tokens, delete parent node + if (empty($children)) { + return false; + } + + // if li is not allowed, delete parent node + if (!isset($config->getHTMLDefinition()->info['li'])) { + trigger_error("Cannot allow ul/ol without allowing li", E_USER_WARNING); + return false; + } + + // the new set of children + $result = array(); + + // a little sanity check to make sure it's not ALL whitespace + $all_whitespace = true; + + $current_li = null; + + foreach ($children as $node) { + if (!empty($node->is_whitespace)) { + $result[] = $node; + continue; + } + $all_whitespace = false; // phew, we're not talking about whitespace + + if ($node->name === 'li') { + // good + $current_li = $node; + $result[] = $node; + } else { + // we want to tuck this into the previous li + // Invariant: we expect the node to be ol/ul + // ToDo: Make this more robust in the case of not ol/ul + // by distinguishing between existing li and li created + // to handle non-list elements; non-list elements should + // not be appended to an existing li; only li created + // for non-list. This distinction is not currently made. + if ($current_li === null) { + $current_li = new HTMLPurifier_Node_Element('li'); + $result[] = $current_li; + } + $current_li->children[] = $node; + $current_li->empty = false; // XXX fascinating! Check for this error elsewhere ToDo + } + } + if (empty($result)) { + return false; + } + if ($all_whitespace) { + return false; + } + return $result; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ChildDef/Optional.php b/tools/htmlpurifier/HTMLPurifier/ChildDef/Optional.php new file mode 100644 index 000000000..b9468063b --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ChildDef/Optional.php @@ -0,0 +1,45 @@ +whitespace) { + return $children; + } else { + return array(); + } + } + return $result; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ChildDef/Required.php b/tools/htmlpurifier/HTMLPurifier/ChildDef/Required.php new file mode 100644 index 000000000..0d1c8f5f3 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ChildDef/Required.php @@ -0,0 +1,118 @@ + $x) { + $elements[$i] = true; + if (empty($i)) { + unset($elements[$i]); + } // remove blank + } + } + $this->elements = $elements; + } + + /** + * @type bool + */ + public $allow_empty = false; + + /** + * @type string + */ + public $type = 'required'; + + /** + * @param array $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function validateChildren($children, $config, $context) + { + // Flag for subclasses + $this->whitespace = false; + + // if there are no tokens, delete parent node + if (empty($children)) { + return false; + } + + // the new set of children + $result = array(); + + // whether or not parsed character data is allowed + // this controls whether or not we silently drop a tag + // or generate escaped HTML from it + $pcdata_allowed = isset($this->elements['#PCDATA']); + + // a little sanity check to make sure it's not ALL whitespace + $all_whitespace = true; + + $stack = array_reverse($children); + while (!empty($stack)) { + $node = array_pop($stack); + if (!empty($node->is_whitespace)) { + $result[] = $node; + continue; + } + $all_whitespace = false; // phew, we're not talking about whitespace + + if (!isset($this->elements[$node->name])) { + // special case text + // XXX One of these ought to be redundant or something + if ($pcdata_allowed && $node instanceof HTMLPurifier_Node_Text) { + $result[] = $node; + continue; + } + // spill the child contents in + // ToDo: Make configurable + if ($node instanceof HTMLPurifier_Node_Element) { + for ($i = count($node->children) - 1; $i >= 0; $i--) { + $stack[] = $node->children[$i]; + } + continue; + } + continue; + } + $result[] = $node; + } + if (empty($result)) { + return false; + } + if ($all_whitespace) { + $this->whitespace = true; + return false; + } + return $result; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ChildDef/StrictBlockquote.php b/tools/htmlpurifier/HTMLPurifier/ChildDef/StrictBlockquote.php new file mode 100644 index 000000000..3270a46e1 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ChildDef/StrictBlockquote.php @@ -0,0 +1,110 @@ +init($config); + return $this->fake_elements; + } + + /** + * @param array $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function validateChildren($children, $config, $context) + { + $this->init($config); + + // trick the parent class into thinking it allows more + $this->elements = $this->fake_elements; + $result = parent::validateChildren($children, $config, $context); + $this->elements = $this->real_elements; + + if ($result === false) { + return array(); + } + if ($result === true) { + $result = $children; + } + + $def = $config->getHTMLDefinition(); + $block_wrap_name = $def->info_block_wrapper; + $block_wrap = false; + $ret = array(); + + foreach ($result as $node) { + if ($block_wrap === false) { + if (($node instanceof HTMLPurifier_Node_Text && !$node->is_whitespace) || + ($node instanceof HTMLPurifier_Node_Element && !isset($this->elements[$node->name]))) { + $block_wrap = new HTMLPurifier_Node_Element($def->info_block_wrapper); + $ret[] = $block_wrap; + } + } else { + if ($node instanceof HTMLPurifier_Node_Element && isset($this->elements[$node->name])) { + $block_wrap = false; + + } + } + if ($block_wrap) { + $block_wrap->children[] = $node; + } else { + $ret[] = $node; + } + } + return $ret; + } + + /** + * @param HTMLPurifier_Config $config + */ + private function init($config) + { + if (!$this->init) { + $def = $config->getHTMLDefinition(); + // allow all inline elements + $this->real_elements = $this->elements; + $this->fake_elements = $def->info_content_sets['Flow']; + $this->fake_elements['#PCDATA'] = true; + $this->init = true; + } + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ChildDef/Table.php b/tools/htmlpurifier/HTMLPurifier/ChildDef/Table.php new file mode 100644 index 000000000..cb6b3e6cd --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ChildDef/Table.php @@ -0,0 +1,224 @@ + true, + 'tbody' => true, + 'thead' => true, + 'tfoot' => true, + 'caption' => true, + 'colgroup' => true, + 'col' => true + ); + + public function __construct() + { + } + + /** + * @param array $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function validateChildren($children, $config, $context) + { + if (empty($children)) { + return false; + } + + // only one of these elements is allowed in a table + $caption = false; + $thead = false; + $tfoot = false; + + // whitespace + $initial_ws = array(); + $after_caption_ws = array(); + $after_thead_ws = array(); + $after_tfoot_ws = array(); + + // as many of these as you want + $cols = array(); + $content = array(); + + $tbody_mode = false; // if true, then we need to wrap any stray + //

+ + + + + +
OriginalTextAttribute
&yen;¥¥
&yen¥¥
&yena&yena&yena
&yen=¥=¥=
+

+ In HTML Purifier 4.9.0, we changed the behavior of entity parsing + to match entities that had missing trailing semicolons in less + cases, to more closely match HTML5 parsing behavior: +

+ + + + + + +
OriginalTextAttribute
&yen;¥¥
&yen¥¥
&yena¥a&yena
&yen=¥=&yen=
+

+ This flag reverts back to pre-HTML Purifier 4.9.0 behavior. +

+--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt similarity index 72% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt index a64e3d7c3..6ed70b599 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt @@ -4,6 +4,6 @@ VERSION: 2.0.1 DEFAULT: NULL --DESCRIPTION-- -A custom doctype for power-users who defined there own document +A custom doctype for power-users who defined their own document type. This directive only applies when %HTML.Doctype is blank. --# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Forms.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Forms.txt new file mode 100644 index 000000000..4a432d89b --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Forms.txt @@ -0,0 +1,11 @@ +HTML.Forms +TYPE: bool +VERSION: 4.13.0 +DEFAULT: false +--DESCRIPTION-- +

+ Whether or not to permit form elements in the user input, regardless of + %HTML.Trusted value. Please be very careful when using this functionality, as + enabling forms in untrusted documents may allow for phishing attacks. +

+--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt new file mode 100644 index 000000000..dd514c0de --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt @@ -0,0 +1,10 @@ +--# vim: et sw=4 sts=4 +HTML.TargetNoopener +TYPE: bool +VERSION: 4.8.0 +DEFAULT: TRUE +--DESCRIPTION-- +If enabled, noopener rel attributes are added to links which have +a target attribute associated with them. This prevents malicious +destinations from overwriting the original window. +--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt new file mode 100644 index 000000000..cb5a0b0e5 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt @@ -0,0 +1,9 @@ +HTML.TargetNoreferrer +TYPE: bool +VERSION: 4.8.0 +DEFAULT: TRUE +--DESCRIPTION-- +If enabled, noreferrer rel attributes are added to links which have +a target attribute associated with them. This prevents malicious +destinations from overwriting the original window. +--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt similarity index 96% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt index 666635a5f..eb97307e2 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt @@ -8,6 +8,7 @@ array ( 'ftp' => true, 'nntp' => true, 'news' => true, + 'tel' => true, ) --DESCRIPTION-- Whitelist that defines the schemes that a URI is allowed to have. This diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Base.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Base.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Base.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Base.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt similarity index 57% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt index 728e378cb..834bc08c0 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt @@ -1,5 +1,5 @@ URI.DefaultScheme -TYPE: string +TYPE: string/null DEFAULT: 'http' --DESCRIPTION-- @@ -7,4 +7,9 @@ DEFAULT: 'http' Defines through what scheme the output will be served, in order to select the proper object validator when no scheme information is present.

+ +

+ Starting with HTML Purifier 4.9.0, the default scheme can be null, in + which case we reject all URIs which do not have explicit schemes. +

--# vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Host.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Host.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Host.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Host.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt diff --git a/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/index.php b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/info.ini b/tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/info.ini similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/ConfigSchema/schema/info.ini rename to tools/htmlpurifier/HTMLPurifier/ConfigSchema/schema/info.ini diff --git a/tools/htmlpurifier/HTMLPurifier/ContentSets.php b/tools/htmlpurifier/HTMLPurifier/ContentSets.php new file mode 100644 index 000000000..543e3f8f1 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ContentSets.php @@ -0,0 +1,170 @@ + true) indexed by name. + * @type array + * @note This is in HTMLPurifier_HTMLDefinition->info_content_sets + */ + public $lookup = array(); + + /** + * Synchronized list of defined content sets (keys of info). + * @type array + */ + protected $keys = array(); + /** + * Synchronized list of defined content values (values of info). + * @type array + */ + protected $values = array(); + + /** + * Merges in module's content sets, expands identifiers in the content + * sets and populates the keys, values and lookup member variables. + * @param HTMLPurifier_HTMLModule[] $modules List of HTMLPurifier_HTMLModule + */ + public function __construct($modules) + { + if (!is_array($modules)) { + $modules = array($modules); + } + // populate content_sets based on module hints + // sorry, no way of overloading + foreach ($modules as $module) { + foreach ($module->content_sets as $key => $value) { + $temp = $this->convertToLookup($value); + if (isset($this->lookup[$key])) { + // add it into the existing content set + $this->lookup[$key] = array_merge($this->lookup[$key], $temp); + } else { + $this->lookup[$key] = $temp; + } + } + } + $old_lookup = false; + while ($old_lookup !== $this->lookup) { + $old_lookup = $this->lookup; + foreach ($this->lookup as $i => $set) { + $add = array(); + foreach ($set as $element => $x) { + if (isset($this->lookup[$element])) { + $add += $this->lookup[$element]; + unset($this->lookup[$i][$element]); + } + } + $this->lookup[$i] += $add; + } + } + + foreach ($this->lookup as $key => $lookup) { + $this->info[$key] = implode(' | ', array_keys($lookup)); + } + $this->keys = array_keys($this->info); + $this->values = array_values($this->info); + } + + /** + * Accepts a definition; generates and assigns a ChildDef for it + * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef reference + * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef + */ + public function generateChildDef(&$def, $module) + { + if (!empty($def->child)) { // already done! + return; + } + $content_model = $def->content_model; + if (is_string($content_model)) { + // Assume that $this->keys is alphanumeric + $def->content_model = preg_replace_callback( + '/\b(' . implode('|', $this->keys) . ')\b/', + array($this, 'generateChildDefCallback'), + $content_model + ); + //$def->content_model = str_replace( + // $this->keys, $this->values, $content_model); + } + $def->child = $this->getChildDef($def, $module); + } + + public function generateChildDefCallback($matches) + { + return $this->info[$matches[0]]; + } + + /** + * Instantiates a ChildDef based on content_model and content_model_type + * member variables in HTMLPurifier_ElementDef + * @note This will also defer to modules for custom HTMLPurifier_ChildDef + * subclasses that need content set expansion + * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef to have ChildDef extracted + * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef + * @return HTMLPurifier_ChildDef corresponding to ElementDef + */ + public function getChildDef($def, $module) + { + $value = $def->content_model; + if (is_object($value)) { + trigger_error( + 'Literal object child definitions should be stored in '. + 'ElementDef->child not ElementDef->content_model', + E_USER_NOTICE + ); + return $value; + } + switch ($def->content_model_type) { + case 'required': + return new HTMLPurifier_ChildDef_Required($value); + case 'optional': + return new HTMLPurifier_ChildDef_Optional($value); + case 'empty': + return new HTMLPurifier_ChildDef_Empty(); + case 'custom': + return new HTMLPurifier_ChildDef_Custom($value); + } + // defer to its module + $return = false; + if ($module->defines_child_def) { // save a func call + $return = $module->getChildDef($def); + } + if ($return !== false) { + return $return; + } + // error-out + trigger_error( + 'Could not determine which ChildDef class to instantiate', + E_USER_ERROR + ); + return false; + } + + /** + * Converts a string list of elements separated by pipes into + * a lookup array. + * @param string $string List of elements + * @return array Lookup array of elements + */ + protected function convertToLookup($string) + { + $array = explode('|', str_replace(' ', '', $string)); + $ret = array(); + foreach ($array as $k) { + $ret[$k] = true; + } + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/Context.php b/tools/htmlpurifier/HTMLPurifier/Context.php new file mode 100644 index 000000000..00e509c85 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/Context.php @@ -0,0 +1,95 @@ +_storage)) { + trigger_error( + "Name $name produces collision, cannot re-register", + E_USER_ERROR + ); + return; + } + $this->_storage[$name] =& $ref; + } + + /** + * Retrieves a variable reference from the context. + * @param string $name String name + * @param bool $ignore_error Boolean whether or not to ignore error + * @return mixed + */ + public function &get($name, $ignore_error = false) + { + if (!array_key_exists($name, $this->_storage)) { + if (!$ignore_error) { + trigger_error( + "Attempted to retrieve non-existent variable $name", + E_USER_ERROR + ); + } + $var = null; // so we can return by reference + return $var; + } + return $this->_storage[$name]; + } + + /** + * Destroys a variable in the context. + * @param string $name String name + */ + public function destroy($name) + { + if (!array_key_exists($name, $this->_storage)) { + trigger_error( + "Attempted to destroy non-existent variable $name", + E_USER_ERROR + ); + return; + } + unset($this->_storage[$name]); + } + + /** + * Checks whether or not the variable exists. + * @param string $name String name + * @return bool + */ + public function exists($name) + { + return array_key_exists($name, $this->_storage); + } + + /** + * Loads a series of variables from an associative array + * @param array $context_array Assoc array of variables to load + */ + public function loadArray($context_array) + { + foreach ($context_array as $key => $discard) { + $this->register($key, $context_array[$key]); + } + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/Definition.php b/tools/htmlpurifier/HTMLPurifier/Definition.php new file mode 100644 index 000000000..bc6d43364 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/Definition.php @@ -0,0 +1,55 @@ +setup) { + return; + } + $this->setup = true; + $this->doSetup($config); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/DefinitionCache.php b/tools/htmlpurifier/HTMLPurifier/DefinitionCache.php new file mode 100644 index 000000000..9aa8ff354 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/DefinitionCache.php @@ -0,0 +1,129 @@ +type = $type; + } + + /** + * Generates a unique identifier for a particular configuration + * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config + * @return string + */ + public function generateKey($config) + { + return $config->version . ',' . // possibly replace with function calls + $config->getBatchSerial($this->type) . ',' . + $config->get($this->type . '.DefinitionRev'); + } + + /** + * Tests whether or not a key is old with respect to the configuration's + * version and revision number. + * @param string $key Key to test + * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config to test against + * @return bool + */ + public function isOld($key, $config) + { + if (substr_count($key, ',') < 2) { + return true; + } + list($version, $hash, $revision) = explode(',', $key, 3); + $compare = version_compare($version, $config->version); + // version mismatch, is always old + if ($compare != 0) { + return true; + } + // versions match, ids match, check revision number + if ($hash == $config->getBatchSerial($this->type) && + $revision < $config->get($this->type . '.DefinitionRev')) { + return true; + } + return false; + } + + /** + * Checks if a definition's type jives with the cache's type + * @note Throws an error on failure + * @param HTMLPurifier_Definition $def Definition object to check + * @return bool true if good, false if not + */ + public function checkDefType($def) + { + if ($def->type !== $this->type) { + trigger_error("Cannot use definition of type {$def->type} in cache for {$this->type}"); + return false; + } + return true; + } + + /** + * Adds a definition object to the cache + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + */ + abstract public function add($def, $config); + + /** + * Unconditionally saves a definition object to the cache + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + */ + abstract public function set($def, $config); + + /** + * Replace an object in the cache + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + */ + abstract public function replace($def, $config); + + /** + * Retrieves a definition object from the cache + * @param HTMLPurifier_Config $config + */ + abstract public function get($config); + + /** + * Removes a definition object to the cache + * @param HTMLPurifier_Config $config + */ + abstract public function remove($config); + + /** + * Clears all objects from cache + * @param HTMLPurifier_Config $config + */ + abstract public function flush($config); + + /** + * Clears all expired (older version or revision) objects from cache + * @note Be careful implementing this method as flush. Flush must + * not interfere with other Definition types, and cleanup() + * should not be repeatedly called by userland code. + * @param HTMLPurifier_Config $config + */ + abstract public function cleanup($config); +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Decorator.php b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Decorator.php new file mode 100644 index 000000000..b57a51b6c --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Decorator.php @@ -0,0 +1,112 @@ +copy(); + // reference is necessary for mocks in PHP 4 + $decorator->cache =& $cache; + $decorator->type = $cache->type; + return $decorator; + } + + /** + * Cross-compatible clone substitute + * @return HTMLPurifier_DefinitionCache_Decorator + */ + public function copy() + { + return new HTMLPurifier_DefinitionCache_Decorator(); + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function add($def, $config) + { + return $this->cache->add($def, $config); + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function set($def, $config) + { + return $this->cache->set($def, $config); + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function replace($def, $config) + { + return $this->cache->replace($def, $config); + } + + /** + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function get($config) + { + return $this->cache->get($config); + } + + /** + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function remove($config) + { + return $this->cache->remove($config); + } + + /** + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function flush($config) + { + return $this->cache->flush($config); + } + + /** + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function cleanup($config) + { + return $this->cache->cleanup($config); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php new file mode 100644 index 000000000..4991777ce --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php @@ -0,0 +1,78 @@ +definitions[$this->generateKey($config)] = $def; + } + return $status; + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function set($def, $config) + { + $status = parent::set($def, $config); + if ($status) { + $this->definitions[$this->generateKey($config)] = $def; + } + return $status; + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function replace($def, $config) + { + $status = parent::replace($def, $config); + if ($status) { + $this->definitions[$this->generateKey($config)] = $def; + } + return $status; + } + + /** + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function get($config) + { + $key = $this->generateKey($config); + if (isset($this->definitions[$key])) { + return $this->definitions[$key]; + } + $this->definitions[$key] = parent::get($config); + return $this->definitions[$key]; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Decorator/Template.php.in b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Decorator/Template.php.in new file mode 100644 index 000000000..b1fec8d36 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Decorator/Template.php.in @@ -0,0 +1,82 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Null.php b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Null.php new file mode 100644 index 000000000..d9a75ce22 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Null.php @@ -0,0 +1,76 @@ +checkDefType($def)) { + return; + } + $file = $this->generateFilePath($config); + if (file_exists($file)) { + return false; + } + if (!$this->_prepareDir($config)) { + return false; + } + return $this->_write($file, serialize($def), $config); + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return int|bool + */ + public function set($def, $config) + { + if (!$this->checkDefType($def)) { + return; + } + $file = $this->generateFilePath($config); + if (!$this->_prepareDir($config)) { + return false; + } + return $this->_write($file, serialize($def), $config); + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return int|bool + */ + public function replace($def, $config) + { + if (!$this->checkDefType($def)) { + return; + } + $file = $this->generateFilePath($config); + if (!file_exists($file)) { + return false; + } + if (!$this->_prepareDir($config)) { + return false; + } + return $this->_write($file, serialize($def), $config); + } + + /** + * @param HTMLPurifier_Config $config + * @return bool|HTMLPurifier_Config + */ + public function get($config) + { + $file = $this->generateFilePath($config); + if (!file_exists($file)) { + return false; + } + return unserialize(file_get_contents($file)); + } + + /** + * @param HTMLPurifier_Config $config + * @return bool + */ + public function remove($config) + { + $file = $this->generateFilePath($config); + if (!file_exists($file)) { + return false; + } + return unlink($file); + } + + /** + * @param HTMLPurifier_Config $config + * @return bool + */ + public function flush($config) + { + if (!$this->_prepareDir($config)) { + return false; + } + $dir = $this->generateDirectoryPath($config); + $dh = opendir($dir); + // Apparently, on some versions of PHP, readdir will return + // an empty string if you pass an invalid argument to readdir. + // So you need this test. See #49. + if (false === $dh) { + return false; + } + while (false !== ($filename = readdir($dh))) { + if (empty($filename)) { + continue; + } + if ($filename[0] === '.') { + continue; + } + unlink($dir . '/' . $filename); + } + closedir($dh); + return true; + } + + /** + * @param HTMLPurifier_Config $config + * @return bool + */ + public function cleanup($config) + { + if (!$this->_prepareDir($config)) { + return false; + } + $dir = $this->generateDirectoryPath($config); + $dh = opendir($dir); + // See #49 (and above). + if (false === $dh) { + return false; + } + while (false !== ($filename = readdir($dh))) { + if (empty($filename)) { + continue; + } + if ($filename[0] === '.') { + continue; + } + $key = substr($filename, 0, strlen($filename) - 4); + if ($this->isOld($key, $config)) { + unlink($dir . '/' . $filename); + } + } + closedir($dh); + return true; + } + + /** + * Generates the file path to the serial file corresponding to + * the configuration and definition name + * @param HTMLPurifier_Config $config + * @return string + * @todo Make protected + */ + public function generateFilePath($config) + { + $key = $this->generateKey($config); + return $this->generateDirectoryPath($config) . '/' . $key . '.ser'; + } + + /** + * Generates the path to the directory contain this cache's serial files + * @param HTMLPurifier_Config $config + * @return string + * @note No trailing slash + * @todo Make protected + */ + public function generateDirectoryPath($config) + { + $base = $this->generateBaseDirectoryPath($config); + return $base . '/' . $this->type; + } + + /** + * Generates path to base directory that contains all definition type + * serials + * @param HTMLPurifier_Config $config + * @return mixed|string + * @todo Make protected + */ + public function generateBaseDirectoryPath($config) + { + $base = $config->get('Cache.SerializerPath'); + $base = is_null($base) ? HTMLPURIFIER_PREFIX . '/HTMLPurifier/DefinitionCache/Serializer' : $base; + return $base; + } + + /** + * Convenience wrapper function for file_put_contents + * @param string $file File name to write to + * @param string $data Data to write into file + * @param HTMLPurifier_Config $config + * @return int|bool Number of bytes written if success, or false if failure. + */ + private function _write($file, $data, $config) + { + $result = file_put_contents($file, $data); + if ($result !== false) { + // set permissions of the new file (no execute) + $chmod = $config->get('Cache.SerializerPermissions'); + if ($chmod !== null) { + chmod($file, $chmod & 0666); + } + } + return $result; + } + + /** + * Prepares the directory that this type stores the serials in + * @param HTMLPurifier_Config $config + * @return bool True if successful + */ + private function _prepareDir($config) + { + $directory = $this->generateDirectoryPath($config); + $chmod = $config->get('Cache.SerializerPermissions'); + if ($chmod === null) { + if (!@mkdir($directory) && !is_dir($directory)) { + trigger_error( + 'Could not create directory ' . $directory . '', + E_USER_WARNING + ); + return false; + } + return true; + } + if (!is_dir($directory)) { + $base = $this->generateBaseDirectoryPath($config); + if (!is_dir($base)) { + trigger_error( + 'Base directory ' . $base . ' does not exist, + please create or change using %Cache.SerializerPath', + E_USER_WARNING + ); + return false; + } elseif (!$this->_testPermissions($base, $chmod)) { + return false; + } + if (!@mkdir($directory, $chmod) && !is_dir($directory)) { + trigger_error( + 'Could not create directory ' . $directory . '', + E_USER_WARNING + ); + return false; + } + if (!$this->_testPermissions($directory, $chmod)) { + return false; + } + } elseif (!$this->_testPermissions($directory, $chmod)) { + return false; + } + return true; + } + + /** + * Tests permissions on a directory and throws out friendly + * error messages and attempts to chmod it itself if possible + * @param string $dir Directory path + * @param int $chmod Permissions + * @return bool True if directory is writable + */ + private function _testPermissions($dir, $chmod) + { + // early abort, if it is writable, everything is hunky-dory + if (is_writable($dir)) { + return true; + } + if (!is_dir($dir)) { + // generally, you'll want to handle this beforehand + // so a more specific error message can be given + trigger_error( + 'Directory ' . $dir . ' does not exist', + E_USER_WARNING + ); + return false; + } + if (function_exists('posix_getuid') && $chmod !== null) { + // POSIX system, we can give more specific advice + if (fileowner($dir) === posix_getuid()) { + // we can chmod it ourselves + $chmod = $chmod | 0700; + if (chmod($dir, $chmod)) { + return true; + } + } elseif (filegroup($dir) === posix_getgid()) { + $chmod = $chmod | 0070; + } else { + // PHP's probably running as nobody, so we'll + // need to give global permissions + $chmod = $chmod | 0777; + } + trigger_error( + 'Directory ' . $dir . ' not writable, ' . + 'please chmod to ' . decoct($chmod), + E_USER_WARNING + ); + } else { + // generic error message + trigger_error( + 'Directory ' . $dir . ' not writable, ' . + 'please alter file permissions', + E_USER_WARNING + ); + } + return false; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/README b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/README new file mode 100755 index 000000000..2e35c1c3d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/README @@ -0,0 +1,3 @@ +This is a dummy file to prevent Git from ignoring this empty directory. + + vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/index.php b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/HTMLPurifier/DefinitionCache/index.php b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/DefinitionCache/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/HTMLPurifier/DefinitionCacheFactory.php b/tools/htmlpurifier/HTMLPurifier/DefinitionCacheFactory.php new file mode 100644 index 000000000..fd1cc9be4 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/DefinitionCacheFactory.php @@ -0,0 +1,106 @@ + array()); + + /** + * @type array + */ + protected $implementations = array(); + + /** + * @type HTMLPurifier_DefinitionCache_Decorator[] + */ + protected $decorators = array(); + + /** + * Initialize default decorators + */ + public function setup() + { + $this->addDecorator('Cleanup'); + } + + /** + * Retrieves an instance of global definition cache factory. + * @param HTMLPurifier_DefinitionCacheFactory $prototype + * @return HTMLPurifier_DefinitionCacheFactory + */ + public static function instance($prototype = null) + { + static $instance; + if ($prototype !== null) { + $instance = $prototype; + } elseif ($instance === null || $prototype === true) { + $instance = new HTMLPurifier_DefinitionCacheFactory(); + $instance->setup(); + } + return $instance; + } + + /** + * Registers a new definition cache object + * @param string $short Short name of cache object, for reference + * @param string $long Full class name of cache object, for construction + */ + public function register($short, $long) + { + $this->implementations[$short] = $long; + } + + /** + * Factory method that creates a cache object based on configuration + * @param string $type Name of definitions handled by cache + * @param HTMLPurifier_Config $config Config instance + * @return mixed + */ + public function create($type, $config) + { + $method = $config->get('Cache.DefinitionImpl'); + if ($method === null) { + return new HTMLPurifier_DefinitionCache_Null($type); + } + if (!empty($this->caches[$method][$type])) { + return $this->caches[$method][$type]; + } + if (isset($this->implementations[$method]) && + class_exists($class = $this->implementations[$method], false)) { + $cache = new $class($type); + } else { + if ($method != 'Serializer') { + trigger_error("Unrecognized DefinitionCache $method, using Serializer instead", E_USER_WARNING); + } + $cache = new HTMLPurifier_DefinitionCache_Serializer($type); + } + foreach ($this->decorators as $decorator) { + $new_cache = $decorator->decorate($cache); + // prevent infinite recursion in PHP 4 + unset($cache); + $cache = $new_cache; + } + $this->caches[$method][$type] = $cache; + return $this->caches[$method][$type]; + } + + /** + * Registers a decorator to add to all new cache objects + * @param HTMLPurifier_DefinitionCache_Decorator|string $decorator An instance or the name of a decorator + */ + public function addDecorator($decorator) + { + if (is_string($decorator)) { + $class = "HTMLPurifier_DefinitionCache_Decorator_$decorator"; + $decorator = new $class; + } + $this->decorators[$decorator->name] = $decorator; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/Doctype.php b/tools/htmlpurifier/HTMLPurifier/Doctype.php new file mode 100644 index 000000000..4acd06e5b --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/Doctype.php @@ -0,0 +1,73 @@ +renderDoctype. + * If structure changes, please update that function. + */ +class HTMLPurifier_Doctype +{ + /** + * Full name of doctype + * @type string + */ + public $name; + + /** + * List of standard modules (string identifiers or literal objects) + * that this doctype uses + * @type array + */ + public $modules = array(); + + /** + * List of modules to use for tidying up code + * @type array + */ + public $tidyModules = array(); + + /** + * Is the language derived from XML (i.e. XHTML)? + * @type bool + */ + public $xml = true; + + /** + * List of aliases for this doctype + * @type array + */ + public $aliases = array(); + + /** + * Public DTD identifier + * @type string + */ + public $dtdPublic; + + /** + * System DTD identifier + * @type string + */ + public $dtdSystem; + + public function __construct( + $name = null, + $xml = true, + $modules = array(), + $tidyModules = array(), + $aliases = array(), + $dtd_public = null, + $dtd_system = null + ) { + $this->name = $name; + $this->xml = $xml; + $this->modules = $modules; + $this->tidyModules = $tidyModules; + $this->aliases = $aliases; + $this->dtdPublic = $dtd_public; + $this->dtdSystem = $dtd_system; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/DoctypeRegistry.php b/tools/htmlpurifier/HTMLPurifier/DoctypeRegistry.php new file mode 100644 index 000000000..acc1d64a6 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/DoctypeRegistry.php @@ -0,0 +1,142 @@ +doctypes[$doctype->name] = $doctype; + $name = $doctype->name; + // hookup aliases + foreach ($doctype->aliases as $alias) { + if (isset($this->doctypes[$alias])) { + continue; + } + $this->aliases[$alias] = $name; + } + // remove old aliases + if (isset($this->aliases[$name])) { + unset($this->aliases[$name]); + } + return $doctype; + } + + /** + * Retrieves reference to a doctype of a certain name + * @note This function resolves aliases + * @note When possible, use the more fully-featured make() + * @param string $doctype Name of doctype + * @return HTMLPurifier_Doctype Editable doctype object + */ + public function get($doctype) + { + if (isset($this->aliases[$doctype])) { + $doctype = $this->aliases[$doctype]; + } + if (!isset($this->doctypes[$doctype])) { + trigger_error('Doctype ' . htmlspecialchars($doctype) . ' does not exist', E_USER_ERROR); + $anon = new HTMLPurifier_Doctype($doctype); + return $anon; + } + return $this->doctypes[$doctype]; + } + + /** + * Creates a doctype based on a configuration object, + * will perform initialization on the doctype + * @note Use this function to get a copy of doctype that config + * can hold on to (this is necessary in order to tell + * Generator whether or not the current document is XML + * based or not). + * @param HTMLPurifier_Config $config + * @return HTMLPurifier_Doctype + */ + public function make($config) + { + return clone $this->get($this->getDoctypeFromConfig($config)); + } + + /** + * Retrieves the doctype from the configuration object + * @param HTMLPurifier_Config $config + * @return string + */ + public function getDoctypeFromConfig($config) + { + // recommended test + $doctype = $config->get('HTML.Doctype'); + if (!empty($doctype)) { + return $doctype; + } + $doctype = $config->get('HTML.CustomDoctype'); + if (!empty($doctype)) { + return $doctype; + } + // backwards-compatibility + if ($config->get('HTML.XHTML')) { + $doctype = 'XHTML 1.0'; + } else { + $doctype = 'HTML 4.01'; + } + if ($config->get('HTML.Strict')) { + $doctype .= ' Strict'; + } else { + $doctype .= ' Transitional'; + } + return $doctype; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ElementDef.php b/tools/htmlpurifier/HTMLPurifier/ElementDef.php new file mode 100644 index 000000000..d5311cedc --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ElementDef.php @@ -0,0 +1,216 @@ +setup(), this array may also + * contain an array at index 0 that indicates which attribute + * collections to load into the full array. It may also + * contain string indentifiers in lieu of HTMLPurifier_AttrDef, + * see HTMLPurifier_AttrTypes on how they are expanded during + * HTMLPurifier_HTMLDefinition->setup() processing. + */ + public $attr = array(); + + // XXX: Design note: currently, it's not possible to override + // previously defined AttrTransforms without messing around with + // the final generated config. This is by design; a previous version + // used an associated list of attr_transform, but it was extremely + // easy to accidentally override other attribute transforms by + // forgetting to specify an index (and just using 0.) While we + // could check this by checking the index number and complaining, + // there is a second problem which is that it is not at all easy to + // tell when something is getting overridden. Combine this with a + // codebase where this isn't really being used, and it's perfect for + // nuking. + + /** + * List of tags HTMLPurifier_AttrTransform to be done before validation. + * @type array + */ + public $attr_transform_pre = array(); + + /** + * List of tags HTMLPurifier_AttrTransform to be done after validation. + * @type array + */ + public $attr_transform_post = array(); + + /** + * HTMLPurifier_ChildDef of this tag. + * @type HTMLPurifier_ChildDef + */ + public $child; + + /** + * Abstract string representation of internal ChildDef rules. + * @see HTMLPurifier_ContentSets for how this is parsed and then transformed + * into an HTMLPurifier_ChildDef. + * @warning This is a temporary variable that is not available after + * being processed by HTMLDefinition + * @type string + */ + public $content_model; + + /** + * Value of $child->type, used to determine which ChildDef to use, + * used in combination with $content_model. + * @warning This must be lowercase + * @warning This is a temporary variable that is not available after + * being processed by HTMLDefinition + * @type string + */ + public $content_model_type; + + /** + * Does the element have a content model (#PCDATA | Inline)*? This + * is important for chameleon ins and del processing in + * HTMLPurifier_ChildDef_Chameleon. Dynamically set: modules don't + * have to worry about this one. + * @type bool + */ + public $descendants_are_inline = false; + + /** + * List of the names of required attributes this element has. + * Dynamically populated by HTMLPurifier_HTMLDefinition::getElement() + * @type array + */ + public $required_attr = array(); + + /** + * Lookup table of tags excluded from all descendants of this tag. + * @type array + * @note SGML permits exclusions for all descendants, but this is + * not possible with DTDs or XML Schemas. W3C has elected to + * use complicated compositions of content_models to simulate + * exclusion for children, but we go the simpler, SGML-style + * route of flat-out exclusions, which correctly apply to + * all descendants and not just children. Note that the XHTML + * Modularization Abstract Modules are blithely unaware of such + * distinctions. + */ + public $excludes = array(); + + /** + * This tag is explicitly auto-closed by the following tags. + * @type array + */ + public $autoclose = array(); + + /** + * If a foreign element is found in this element, test if it is + * allowed by this sub-element; if it is, instead of closing the + * current element, place it inside this element. + * @type string + */ + public $wrap; + + /** + * Whether or not this is a formatting element affected by the + * "Active Formatting Elements" algorithm. + * @type bool + */ + public $formatting; + + /** + * Low-level factory constructor for creating new standalone element defs + */ + public static function create($content_model, $content_model_type, $attr) + { + $def = new HTMLPurifier_ElementDef(); + $def->content_model = $content_model; + $def->content_model_type = $content_model_type; + $def->attr = $attr; + return $def; + } + + /** + * Merges the values of another element definition into this one. + * Values from the new element def take precedence if a value is + * not mergeable. + * @param HTMLPurifier_ElementDef $def + */ + public function mergeIn($def) + { + // later keys takes precedence + foreach ($def->attr as $k => $v) { + if ($k === 0) { + // merge in the includes + // sorry, no way to override an include + foreach ($v as $v2) { + $this->attr[0][] = $v2; + } + continue; + } + if ($v === false) { + if (isset($this->attr[$k])) { + unset($this->attr[$k]); + } + continue; + } + $this->attr[$k] = $v; + } + $this->_mergeAssocArray($this->excludes, $def->excludes); + $this->attr_transform_pre = array_merge($this->attr_transform_pre, $def->attr_transform_pre); + $this->attr_transform_post = array_merge($this->attr_transform_post, $def->attr_transform_post); + + if (!empty($def->content_model)) { + $this->content_model = + str_replace("#SUPER", $this->content_model, $def->content_model); + $this->child = false; + } + if (!empty($def->content_model_type)) { + $this->content_model_type = $def->content_model_type; + $this->child = false; + } + if (!is_null($def->child)) { + $this->child = $def->child; + } + if (!is_null($def->formatting)) { + $this->formatting = $def->formatting; + } + if ($def->descendants_are_inline) { + $this->descendants_are_inline = $def->descendants_are_inline; + } + } + + /** + * Merges one array into another, removes values which equal false + * @param $a1 Array by reference that is merged into + * @param $a2 Array that merges into $a1 + */ + private function _mergeAssocArray(&$a1, $a2) + { + foreach ($a2 as $k => $v) { + if ($v === false) { + if (isset($a1[$k])) { + unset($a1[$k]); + } + continue; + } + $a1[$k] = $v; + } + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/Encoder.php b/tools/htmlpurifier/HTMLPurifier/Encoder.php new file mode 100644 index 000000000..40a24266a --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/Encoder.php @@ -0,0 +1,617 @@ += $c) { + $r .= self::unsafeIconv($in, $out, substr($text, $i)); + break; + } + // wibble the boundary + if (0x80 != (0xC0 & ord($text[$i + $max_chunk_size]))) { + $chunk_size = $max_chunk_size; + } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 1]))) { + $chunk_size = $max_chunk_size - 1; + } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 2]))) { + $chunk_size = $max_chunk_size - 2; + } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 3]))) { + $chunk_size = $max_chunk_size - 3; + } else { + return false; // rather confusing UTF-8... + } + $chunk = substr($text, $i, $chunk_size); // substr doesn't mind overlong lengths + $r .= self::unsafeIconv($in, $out, $chunk); + $i += $chunk_size; + } + return $r; + } else { + return false; + } + } else { + return false; + } + } + + /** + * Cleans a UTF-8 string for well-formedness and SGML validity + * + * It will parse according to UTF-8 and return a valid UTF8 string, with + * non-SGML codepoints excluded. + * + * Specifically, it will permit: + * \x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF} + * Source: https://www.w3.org/TR/REC-xml/#NT-Char + * Arguably this function should be modernized to the HTML5 set + * of allowed characters: + * https://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream + * which simultaneously expand and restrict the set of allowed characters. + * + * @param string $str The string to clean + * @param bool $force_php + * @return string + * + * @note Just for reference, the non-SGML code points are 0 to 31 and + * 127 to 159, inclusive. However, we allow code points 9, 10 + * and 13, which are the tab, line feed and carriage return + * respectively. 128 and above the code points map to multibyte + * UTF-8 representations. + * + * @note Fallback code adapted from utf8ToUnicode by Henri Sivonen and + * hsivonen@iki.fi at under the + * LGPL license. Notes on what changed are inside, but in general, + * the original code transformed UTF-8 text into an array of integer + * Unicode codepoints. Understandably, transforming that back to + * a string would be somewhat expensive, so the function was modded to + * directly operate on the string. However, this discourages code + * reuse, and the logic enumerated here would be useful for any + * function that needs to be able to understand UTF-8 characters. + * As of right now, only smart lossless character encoding converters + * would need that, and I'm probably not going to implement them. + */ + public static function cleanUTF8($str, $force_php = false) + { + // UTF-8 validity is checked since PHP 4.3.5 + // This is an optimization: if the string is already valid UTF-8, no + // need to do PHP stuff. 99% of the time, this will be the case. + if (preg_match( + '/^[\x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]*$/Du', + $str + )) { + return $str; + } + + $mState = 0; // cached expected number of octets after the current octet + // until the beginning of the next UTF8 character sequence + $mUcs4 = 0; // cached Unicode character + $mBytes = 1; // cached expected number of octets in the current sequence + + // original code involved an $out that was an array of Unicode + // codepoints. Instead of having to convert back into UTF-8, we've + // decided to directly append valid UTF-8 characters onto a string + // $out once they're done. $char accumulates raw bytes, while $mUcs4 + // turns into the Unicode code point, so there's some redundancy. + + $out = ''; + $char = ''; + + $len = strlen($str); + for ($i = 0; $i < $len; $i++) { + $in = ord($str[$i]); + $char .= $str[$i]; // append byte to char + if (0 == $mState) { + // When mState is zero we expect either a US-ASCII character + // or a multi-octet sequence. + if (0 == (0x80 & ($in))) { + // US-ASCII, pass straight through. + if (($in <= 31 || $in == 127) && + !($in == 9 || $in == 13 || $in == 10) // save \r\t\n + ) { + // control characters, remove + } else { + $out .= $char; + } + // reset + $char = ''; + $mBytes = 1; + } elseif (0xC0 == (0xE0 & ($in))) { + // First octet of 2 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x1F) << 6; + $mState = 1; + $mBytes = 2; + } elseif (0xE0 == (0xF0 & ($in))) { + // First octet of 3 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x0F) << 12; + $mState = 2; + $mBytes = 3; + } elseif (0xF0 == (0xF8 & ($in))) { + // First octet of 4 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x07) << 18; + $mState = 3; + $mBytes = 4; + } elseif (0xF8 == (0xFC & ($in))) { + // First octet of 5 octet sequence. + // + // This is illegal because the encoded codepoint must be + // either: + // (a) not the shortest form or + // (b) outside the Unicode range of 0-0x10FFFF. + // Rather than trying to resynchronize, we will carry on + // until the end of the sequence and let the later error + // handling code catch it. + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x03) << 24; + $mState = 4; + $mBytes = 5; + } elseif (0xFC == (0xFE & ($in))) { + // First octet of 6 octet sequence, see comments for 5 + // octet sequence. + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 1) << 30; + $mState = 5; + $mBytes = 6; + } else { + // Current octet is neither in the US-ASCII range nor a + // legal first octet of a multi-octet sequence. + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + $char = ''; + } + } else { + // When mState is non-zero, we expect a continuation of the + // multi-octet sequence + if (0x80 == (0xC0 & ($in))) { + // Legal continuation. + $shift = ($mState - 1) * 6; + $tmp = $in; + $tmp = ($tmp & 0x0000003F) << $shift; + $mUcs4 |= $tmp; + + if (0 == --$mState) { + // End of the multi-octet sequence. mUcs4 now contains + // the final Unicode codepoint to be output + + // Check for illegal sequences and codepoints. + + // From Unicode 3.1, non-shortest form is illegal + if (((2 == $mBytes) && ($mUcs4 < 0x0080)) || + ((3 == $mBytes) && ($mUcs4 < 0x0800)) || + ((4 == $mBytes) && ($mUcs4 < 0x10000)) || + (4 < $mBytes) || + // From Unicode 3.2, surrogate characters = illegal + (($mUcs4 & 0xFFFFF800) == 0xD800) || + // Codepoints outside the Unicode range are illegal + ($mUcs4 > 0x10FFFF) + ) { + + } elseif (0xFEFF != $mUcs4 && // omit BOM + // check for valid Char unicode codepoints + ( + 0x9 == $mUcs4 || + 0xA == $mUcs4 || + 0xD == $mUcs4 || + (0x20 <= $mUcs4 && 0x7E >= $mUcs4) || + // 7F-9F is not strictly prohibited by XML, + // but it is non-SGML, and thus we don't allow it + (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) || + (0xE000 <= $mUcs4 && 0xFFFD >= $mUcs4) || + (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4) + ) + ) { + $out .= $char; + } + // initialize UTF8 cache (reset) + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + $char = ''; + } + } else { + // ((0xC0 & (*in) != 0x80) && (mState != 0)) + // Incomplete multi-octet sequence. + // used to result in complete fail, but we'll reset + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + $char =''; + } + } + } + return $out; + } + + /** + * Translates a Unicode codepoint into its corresponding UTF-8 character. + * @note Based on Feyd's function at + * , + * which is in public domain. + * @note While we're going to do code point parsing anyway, a good + * optimization would be to refuse to translate code points that + * are non-SGML characters. However, this could lead to duplication. + * @note This is very similar to the unichr function in + * maintenance/generate-entity-file.php (although this is superior, + * due to its sanity checks). + */ + + // +----------+----------+----------+----------+ + // | 33222222 | 22221111 | 111111 | | + // | 10987654 | 32109876 | 54321098 | 76543210 | bit + // +----------+----------+----------+----------+ + // | | | | 0xxxxxxx | 1 byte 0x00000000..0x0000007F + // | | | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF + // | | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF + // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF + // +----------+----------+----------+----------+ + // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF) + // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes + // +----------+----------+----------+----------+ + + public static function unichr($code) + { + if ($code > 1114111 or $code < 0 or + ($code >= 55296 and $code <= 57343) ) { + // bits are set outside the "valid" range as defined + // by UNICODE 4.1.0 + return ''; + } + + $x = $y = $z = $w = 0; + if ($code < 128) { + // regular ASCII character + $x = $code; + } else { + // set up bits for UTF-8 + $x = ($code & 63) | 128; + if ($code < 2048) { + $y = (($code & 2047) >> 6) | 192; + } else { + $y = (($code & 4032) >> 6) | 128; + if ($code < 65536) { + $z = (($code >> 12) & 15) | 224; + } else { + $z = (($code >> 12) & 63) | 128; + $w = (($code >> 18) & 7) | 240; + } + } + } + // set up the actual character + $ret = ''; + if ($w) { + $ret .= chr($w); + } + if ($z) { + $ret .= chr($z); + } + if ($y) { + $ret .= chr($y); + } + $ret .= chr($x); + + return $ret; + } + + /** + * @return bool + */ + public static function iconvAvailable() + { + static $iconv = null; + if ($iconv === null) { + $iconv = function_exists('iconv') && self::testIconvTruncateBug() != self::ICONV_UNUSABLE; + } + return $iconv; + } + + /** + * Convert a string to UTF-8 based on configuration. + * @param string $str The string to convert + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public static function convertToUTF8($str, $config, $context) + { + $encoding = $config->get('Core.Encoding'); + if ($encoding === 'utf-8') { + return $str; + } + static $iconv = null; + if ($iconv === null) { + $iconv = self::iconvAvailable(); + } + if ($iconv && !$config->get('Test.ForceNoIconv')) { + // unaffected by bugs, since UTF-8 support all characters + $str = self::unsafeIconv($encoding, 'utf-8//IGNORE', $str); + if ($str === false) { + // $encoding is not a valid encoding + trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR); + return ''; + } + // If the string is bjorked by Shift_JIS or a similar encoding + // that doesn't support all of ASCII, convert the naughty + // characters to their true byte-wise ASCII/UTF-8 equivalents. + $str = strtr($str, self::testEncodingSupportsASCII($encoding)); + return $str; + } elseif ($encoding === 'iso-8859-1') { + $str = utf8_encode($str); + return $str; + } + $bug = HTMLPurifier_Encoder::testIconvTruncateBug(); + if ($bug == self::ICONV_OK) { + trigger_error('Encoding not supported, please install iconv', E_USER_ERROR); + } else { + trigger_error( + 'You have a buggy version of iconv, see https://bugs.php.net/bug.php?id=48147 ' . + 'and http://sourceware.org/bugzilla/show_bug.cgi?id=13541', + E_USER_ERROR + ); + } + } + + /** + * Converts a string from UTF-8 based on configuration. + * @param string $str The string to convert + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + * @note Currently, this is a lossy conversion, with unexpressable + * characters being omitted. + */ + public static function convertFromUTF8($str, $config, $context) + { + $encoding = $config->get('Core.Encoding'); + if ($escape = $config->get('Core.EscapeNonASCIICharacters')) { + $str = self::convertToASCIIDumbLossless($str); + } + if ($encoding === 'utf-8') { + return $str; + } + static $iconv = null; + if ($iconv === null) { + $iconv = self::iconvAvailable(); + } + if ($iconv && !$config->get('Test.ForceNoIconv')) { + // Undo our previous fix in convertToUTF8, otherwise iconv will barf + $ascii_fix = self::testEncodingSupportsASCII($encoding); + if (!$escape && !empty($ascii_fix)) { + $clear_fix = array(); + foreach ($ascii_fix as $utf8 => $native) { + $clear_fix[$utf8] = ''; + } + $str = strtr($str, $clear_fix); + } + $str = strtr($str, array_flip($ascii_fix)); + // Normal stuff + $str = self::iconv('utf-8', $encoding . '//IGNORE', $str); + return $str; + } elseif ($encoding === 'iso-8859-1') { + $str = utf8_decode($str); + return $str; + } + trigger_error('Encoding not supported', E_USER_ERROR); + // You might be tempted to assume that the ASCII representation + // might be OK, however, this is *not* universally true over all + // encodings. So we take the conservative route here, rather + // than forcibly turn on %Core.EscapeNonASCIICharacters + } + + /** + * Lossless (character-wise) conversion of HTML to ASCII + * @param string $str UTF-8 string to be converted to ASCII + * @return string ASCII encoded string with non-ASCII character entity-ized + * @warning Adapted from MediaWiki, claiming fair use: this is a common + * algorithm. If you disagree with this license fudgery, + * implement it yourself. + * @note Uses decimal numeric entities since they are best supported. + * @note This is a DUMB function: it has no concept of keeping + * character entities that the projected character encoding + * can allow. We could possibly implement a smart version + * but that would require it to also know which Unicode + * codepoints the charset supported (not an easy task). + * @note Sort of with cleanUTF8() but it assumes that $str is + * well-formed UTF-8 + */ + public static function convertToASCIIDumbLossless($str) + { + $bytesleft = 0; + $result = ''; + $working = 0; + $len = strlen($str); + for ($i = 0; $i < $len; $i++) { + $bytevalue = ord($str[$i]); + if ($bytevalue <= 0x7F) { //0xxx xxxx + $result .= chr($bytevalue); + $bytesleft = 0; + } elseif ($bytevalue <= 0xBF) { //10xx xxxx + $working = $working << 6; + $working += ($bytevalue & 0x3F); + $bytesleft--; + if ($bytesleft <= 0) { + $result .= "&#" . $working . ";"; + } + } elseif ($bytevalue <= 0xDF) { //110x xxxx + $working = $bytevalue & 0x1F; + $bytesleft = 1; + } elseif ($bytevalue <= 0xEF) { //1110 xxxx + $working = $bytevalue & 0x0F; + $bytesleft = 2; + } else { //1111 0xxx + $working = $bytevalue & 0x07; + $bytesleft = 3; + } + } + return $result; + } + + /** No bugs detected in iconv. */ + const ICONV_OK = 0; + + /** Iconv truncates output if converting from UTF-8 to another + * character set with //IGNORE, and a non-encodable character is found */ + const ICONV_TRUNCATES = 1; + + /** Iconv does not support //IGNORE, making it unusable for + * transcoding purposes */ + const ICONV_UNUSABLE = 2; + + /** + * glibc iconv has a known bug where it doesn't handle the magic + * //IGNORE stanza correctly. In particular, rather than ignore + * characters, it will return an EILSEQ after consuming some number + * of characters, and expect you to restart iconv as if it were + * an E2BIG. Old versions of PHP did not respect the errno, and + * returned the fragment, so as a result you would see iconv + * mysteriously truncating output. We can work around this by + * manually chopping our input into segments of about 8000 + * characters, as long as PHP ignores the error code. If PHP starts + * paying attention to the error code, iconv becomes unusable. + * + * @return int Error code indicating severity of bug. + */ + public static function testIconvTruncateBug() + { + static $code = null; + if ($code === null) { + // better not use iconv, otherwise infinite loop! + $r = self::unsafeIconv('utf-8', 'ascii//IGNORE', "\xCE\xB1" . str_repeat('a', 9000)); + if ($r === false) { + $code = self::ICONV_UNUSABLE; + } elseif (($c = strlen($r)) < 9000) { + $code = self::ICONV_TRUNCATES; + } elseif ($c > 9000) { + trigger_error( + 'Your copy of iconv is extremely buggy. Please notify HTML Purifier maintainers: ' . + 'include your iconv version as per phpversion()', + E_USER_ERROR + ); + } else { + $code = self::ICONV_OK; + } + } + return $code; + } + + /** + * This expensive function tests whether or not a given character + * encoding supports ASCII. 7/8-bit encodings like Shift_JIS will + * fail this test, and require special processing. Variable width + * encodings shouldn't ever fail. + * + * @param string $encoding Encoding name to test, as per iconv format + * @param bool $bypass Whether or not to bypass the precompiled arrays. + * @return Array of UTF-8 characters to their corresponding ASCII, + * which can be used to "undo" any overzealous iconv action. + */ + public static function testEncodingSupportsASCII($encoding, $bypass = false) + { + // All calls to iconv here are unsafe, proof by case analysis: + // If ICONV_OK, no difference. + // If ICONV_TRUNCATE, all calls involve one character inputs, + // so bug is not triggered. + // If ICONV_UNUSABLE, this call is irrelevant + static $encodings = array(); + if (!$bypass) { + if (isset($encodings[$encoding])) { + return $encodings[$encoding]; + } + $lenc = strtolower($encoding); + switch ($lenc) { + case 'shift_jis': + return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~'); + case 'johab': + return array("\xE2\x82\xA9" => '\\'); + } + if (strpos($lenc, 'iso-8859-') === 0) { + return array(); + } + } + $ret = array(); + if (self::unsafeIconv('UTF-8', $encoding, 'a') === false) { + return false; + } + for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars + $c = chr($i); // UTF-8 char + $r = self::unsafeIconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion + if ($r === '' || + // This line is needed for iconv implementations that do not + // omit characters that do not exist in the target character set + ($r === $c && self::unsafeIconv($encoding, 'UTF-8//IGNORE', $r) !== $c) + ) { + // Reverse engineer: what's the UTF-8 equiv of this byte + // sequence? This assumes that there's no variable width + // encoding that doesn't support ASCII. + $ret[self::unsafeIconv($encoding, 'UTF-8//IGNORE', $c)] = $c; + } + } + $encodings[$encoding] = $ret; + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/EntityLookup.php b/tools/htmlpurifier/HTMLPurifier/EntityLookup.php new file mode 100644 index 000000000..f12ff13a3 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/EntityLookup.php @@ -0,0 +1,48 @@ +table = unserialize(file_get_contents($file)); + } + + /** + * Retrieves sole instance of the object. + * @param bool|HTMLPurifier_EntityLookup $prototype Optional prototype of custom lookup table to overload with. + * @return HTMLPurifier_EntityLookup + */ + public static function instance($prototype = false) + { + // no references, since PHP doesn't copy unless modified + static $instance = null; + if ($prototype) { + $instance = $prototype; + } elseif (!$instance) { + $instance = new HTMLPurifier_EntityLookup(); + $instance->setup(); + } + return $instance; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/EntityLookup/entities.ser b/tools/htmlpurifier/HTMLPurifier/EntityLookup/entities.ser similarity index 100% rename from tools/htmlpurifier/standalone/HTMLPurifier/EntityLookup/entities.ser rename to tools/htmlpurifier/HTMLPurifier/EntityLookup/entities.ser diff --git a/tools/htmlpurifier/HTMLPurifier/EntityLookup/index.php b/tools/htmlpurifier/HTMLPurifier/EntityLookup/index.php new file mode 100644 index 000000000..051e0122d --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/EntityLookup/index.php @@ -0,0 +1,29 @@ + +* @copyright 2010-2021 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../../'); +exit; diff --git a/tools/htmlpurifier/HTMLPurifier/EntityParser.php b/tools/htmlpurifier/HTMLPurifier/EntityParser.php new file mode 100644 index 000000000..3ef2d09ec --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/EntityParser.php @@ -0,0 +1,285 @@ +_semiOptionalPrefixRegex = "/&()()()($semi_optional)/"; + + $this->_textEntitiesRegex = + '/&(?:'. + // hex + '[#]x([a-fA-F0-9]+);?|'. + // dec + '[#]0*(\d+);?|'. + // string (mandatory semicolon) + // NB: order matters: match semicolon preferentially + '([A-Za-z_:][A-Za-z0-9.\-_:]*);|'. + // string (optional semicolon) + "($semi_optional)". + ')/'; + + $this->_attrEntitiesRegex = + '/&(?:'. + // hex + '[#]x([a-fA-F0-9]+);?|'. + // dec + '[#]0*(\d+);?|'. + // string (mandatory semicolon) + // NB: order matters: match semicolon preferentially + '([A-Za-z_:][A-Za-z0-9.\-_:]*);|'. + // string (optional semicolon) + // don't match if trailing is equals or alphanumeric (URL + // like) + "($semi_optional)(?![=;A-Za-z0-9])". + ')/'; + + } + + /** + * Substitute entities with the parsed equivalents. Use this on + * textual data in an HTML document (as opposed to attributes.) + * + * @param string $string String to have entities parsed. + * @return string Parsed string. + */ + public function substituteTextEntities($string) + { + return preg_replace_callback( + $this->_textEntitiesRegex, + array($this, 'entityCallback'), + $string + ); + } + + /** + * Substitute entities with the parsed equivalents. Use this on + * attribute contents in documents. + * + * @param string $string String to have entities parsed. + * @return string Parsed string. + */ + public function substituteAttrEntities($string) + { + return preg_replace_callback( + $this->_attrEntitiesRegex, + array($this, 'entityCallback'), + $string + ); + } + + /** + * Callback function for substituteNonSpecialEntities() that does the work. + * + * @param array $matches PCRE matches array, with 0 the entire match, and + * either index 1, 2 or 3 set with a hex value, dec value, + * or string (respectively). + * @return string Replacement string. + */ + + protected function entityCallback($matches) + { + $entity = $matches[0]; + $hex_part = @$matches[1]; + $dec_part = @$matches[2]; + $named_part = empty($matches[3]) ? (empty($matches[4]) ? "" : $matches[4]) : $matches[3]; + if ($hex_part !== NULL && $hex_part !== "") { + return HTMLPurifier_Encoder::unichr(hexdec($hex_part)); + } elseif ($dec_part !== NULL && $dec_part !== "") { + return HTMLPurifier_Encoder::unichr((int) $dec_part); + } else { + if (!$this->_entity_lookup) { + $this->_entity_lookup = HTMLPurifier_EntityLookup::instance(); + } + if (isset($this->_entity_lookup->table[$named_part])) { + return $this->_entity_lookup->table[$named_part]; + } else { + // exact match didn't match anything, so test if + // any of the semicolon optional match the prefix. + // Test that this is an EXACT match is important to + // prevent infinite loop + if (!empty($matches[3])) { + return preg_replace_callback( + $this->_semiOptionalPrefixRegex, + array($this, 'entityCallback'), + $entity + ); + } + return $entity; + } + } + } + + // LEGACY CODE BELOW + + /** + * Callback regex string for parsing entities. + * @type string + */ + protected $_substituteEntitiesRegex = + '/&(?:[#]x([a-fA-F0-9]+)|[#]0*(\d+)|([A-Za-z_:][A-Za-z0-9.\-_:]*));?/'; + // 1. hex 2. dec 3. string (XML style) + + /** + * Decimal to parsed string conversion table for special entities. + * @type array + */ + protected $_special_dec2str = + array( + 34 => '"', + 38 => '&', + 39 => "'", + 60 => '<', + 62 => '>' + ); + + /** + * Stripped entity names to decimal conversion table for special entities. + * @type array + */ + protected $_special_ent2dec = + array( + 'quot' => 34, + 'amp' => 38, + 'lt' => 60, + 'gt' => 62 + ); + + /** + * Substitutes non-special entities with their parsed equivalents. Since + * running this whenever you have parsed character is t3h 5uck, we run + * it before everything else. + * + * @param string $string String to have non-special entities parsed. + * @return string Parsed string. + */ + public function substituteNonSpecialEntities($string) + { + // it will try to detect missing semicolons, but don't rely on it + return preg_replace_callback( + $this->_substituteEntitiesRegex, + array($this, 'nonSpecialEntityCallback'), + $string + ); + } + + /** + * Callback function for substituteNonSpecialEntities() that does the work. + * + * @param array $matches PCRE matches array, with 0 the entire match, and + * either index 1, 2 or 3 set with a hex value, dec value, + * or string (respectively). + * @return string Replacement string. + */ + + protected function nonSpecialEntityCallback($matches) + { + // replaces all but big five + $entity = $matches[0]; + $is_num = (@$matches[0][1] === '#'); + if ($is_num) { + $is_hex = (@$entity[2] === 'x'); + $code = $is_hex ? hexdec($matches[1]) : (int) $matches[2]; + // abort for special characters + if (isset($this->_special_dec2str[$code])) { + return $entity; + } + return HTMLPurifier_Encoder::unichr($code); + } else { + if (isset($this->_special_ent2dec[$matches[3]])) { + return $entity; + } + if (!$this->_entity_lookup) { + $this->_entity_lookup = HTMLPurifier_EntityLookup::instance(); + } + if (isset($this->_entity_lookup->table[$matches[3]])) { + return $this->_entity_lookup->table[$matches[3]]; + } else { + return $entity; + } + } + } + + /** + * Substitutes only special entities with their parsed equivalents. + * + * @notice We try to avoid calling this function because otherwise, it + * would have to be called a lot (for every parsed section). + * + * @param string $string String to have non-special entities parsed. + * @return string Parsed string. + */ + public function substituteSpecialEntities($string) + { + return preg_replace_callback( + $this->_substituteEntitiesRegex, + array($this, 'specialEntityCallback'), + $string + ); + } + + /** + * Callback function for substituteSpecialEntities() that does the work. + * + * This callback has same syntax as nonSpecialEntityCallback(). + * + * @param array $matches PCRE-style matches array, with 0 the entire match, and + * either index 1, 2 or 3 set with a hex value, dec value, + * or string (respectively). + * @return string Replacement string. + */ + protected function specialEntityCallback($matches) + { + $entity = $matches[0]; + $is_num = (@$matches[0][1] === '#'); + if ($is_num) { + $is_hex = (@$entity[2] === 'x'); + $int = $is_hex ? hexdec($matches[1]) : (int) $matches[2]; + return isset($this->_special_dec2str[$int]) ? + $this->_special_dec2str[$int] : + $entity; + } else { + return isset($this->_special_ent2dec[$matches[3]]) ? + $this->_special_dec2str[$this->_special_ent2dec[$matches[3]]] : + $entity; + } + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ErrorCollector.php b/tools/htmlpurifier/HTMLPurifier/ErrorCollector.php new file mode 100644 index 000000000..d47e3f2e2 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ErrorCollector.php @@ -0,0 +1,244 @@ +locale =& $context->get('Locale'); + $this->context = $context; + $this->_current =& $this->_stacks[0]; + $this->errors =& $this->_stacks[0]; + } + + /** + * Sends an error message to the collector for later use + * @param int $severity Error severity, PHP error style (don't use E_USER_) + * @param string $msg Error message text + */ + public function send($severity, $msg) + { + $args = array(); + if (func_num_args() > 2) { + $args = func_get_args(); + array_shift($args); + unset($args[0]); + } + + $token = $this->context->get('CurrentToken', true); + $line = $token ? $token->line : $this->context->get('CurrentLine', true); + $col = $token ? $token->col : $this->context->get('CurrentCol', true); + $attr = $this->context->get('CurrentAttr', true); + + // perform special substitutions, also add custom parameters + $subst = array(); + if (!is_null($token)) { + $args['CurrentToken'] = $token; + } + if (!is_null($attr)) { + $subst['$CurrentAttr.Name'] = $attr; + if (isset($token->attr[$attr])) { + $subst['$CurrentAttr.Value'] = $token->attr[$attr]; + } + } + + if (empty($args)) { + $msg = $this->locale->getMessage($msg); + } else { + $msg = $this->locale->formatMessage($msg, $args); + } + + if (!empty($subst)) { + $msg = strtr($msg, $subst); + } + + // (numerically indexed) + $error = array( + self::LINENO => $line, + self::SEVERITY => $severity, + self::MESSAGE => $msg, + self::CHILDREN => array() + ); + $this->_current[] = $error; + + // NEW CODE BELOW ... + // Top-level errors are either: + // TOKEN type, if $value is set appropriately, or + // "syntax" type, if $value is null + $new_struct = new HTMLPurifier_ErrorStruct(); + $new_struct->type = HTMLPurifier_ErrorStruct::TOKEN; + if ($token) { + $new_struct->value = clone $token; + } + if (is_int($line) && is_int($col)) { + if (isset($this->lines[$line][$col])) { + $struct = $this->lines[$line][$col]; + } else { + $struct = $this->lines[$line][$col] = $new_struct; + } + // These ksorts may present a performance problem + ksort($this->lines[$line], SORT_NUMERIC); + } else { + if (isset($this->lines[-1])) { + $struct = $this->lines[-1]; + } else { + $struct = $this->lines[-1] = $new_struct; + } + } + ksort($this->lines, SORT_NUMERIC); + + // Now, check if we need to operate on a lower structure + if (!empty($attr)) { + $struct = $struct->getChild(HTMLPurifier_ErrorStruct::ATTR, $attr); + if (!$struct->value) { + $struct->value = array($attr, 'PUT VALUE HERE'); + } + } + if (!empty($cssprop)) { + $struct = $struct->getChild(HTMLPurifier_ErrorStruct::CSSPROP, $cssprop); + if (!$struct->value) { + // if we tokenize CSS this might be a little more difficult to do + $struct->value = array($cssprop, 'PUT VALUE HERE'); + } + } + + // Ok, structs are all setup, now time to register the error + $struct->addError($severity, $msg); + } + + /** + * Retrieves raw error data for custom formatter to use + */ + public function getRaw() + { + return $this->errors; + } + + /** + * Default HTML formatting implementation for error messages + * @param HTMLPurifier_Config $config Configuration, vital for HTML output nature + * @param array $errors Errors array to display; used for recursion. + * @return string + */ + public function getHTMLFormatted($config, $errors = null) + { + $ret = array(); + + $this->generator = new HTMLPurifier_Generator($config, $this->context); + if ($errors === null) { + $errors = $this->errors; + } + + // 'At line' message needs to be removed + + // generation code for new structure goes here. It needs to be recursive. + foreach ($this->lines as $line => $col_array) { + if ($line == -1) { + continue; + } + foreach ($col_array as $col => $struct) { + $this->_renderStruct($ret, $struct, $line, $col); + } + } + if (isset($this->lines[-1])) { + $this->_renderStruct($ret, $this->lines[-1]); + } + + if (empty($errors)) { + return '

' . $this->locale->getMessage('ErrorCollector: No errors') . '

'; + } else { + return '
  • ' . implode('
  • ', $ret) . '
'; + } + + } + + private function _renderStruct(&$ret, $struct, $line = null, $col = null) + { + $stack = array($struct); + $context_stack = array(array()); + while ($current = array_pop($stack)) { + $context = array_pop($context_stack); + foreach ($current->errors as $error) { + list($severity, $msg) = $error; + $string = ''; + $string .= '
'; + // W3C uses an icon to indicate the severity of the error. + $error = $this->locale->getErrorName($severity); + $string .= "$error "; + if (!is_null($line) && !is_null($col)) { + $string .= "Line $line, Column $col: "; + } else { + $string .= 'End of Document: '; + } + $string .= '' . $this->generator->escape($msg) . ' '; + $string .= '
'; + // Here, have a marker for the character on the column appropriate. + // Be sure to clip extremely long lines. + //$string .= '
';
+                //$string .= '';
+                //$string .= '
'; + $ret[] = $string; + } + foreach ($current->children as $array) { + $context[] = $current; + $stack = array_merge($stack, array_reverse($array, true)); + for ($i = count($array); $i > 0; $i--) { + $context_stack[] = $context; + } + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/ErrorStruct.php b/tools/htmlpurifier/HTMLPurifier/ErrorStruct.php new file mode 100644 index 000000000..cf869d321 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/ErrorStruct.php @@ -0,0 +1,74 @@ +children[$type][$id])) { + $this->children[$type][$id] = new HTMLPurifier_ErrorStruct(); + $this->children[$type][$id]->type = $type; + } + return $this->children[$type][$id]; + } + + /** + * @param int $severity + * @param string $message + */ + public function addError($severity, $message) + { + $this->errors[] = array($severity, $message); + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/HTMLPurifier/Exception.php b/tools/htmlpurifier/HTMLPurifier/Exception.php new file mode 100644 index 000000000..be85b4c56 --- /dev/null +++ b/tools/htmlpurifier/HTMLPurifier/Exception.php @@ -0,0 +1,12 @@ +preFilter, + * 2->preFilter, 3->preFilter, purify, 3->postFilter, 2->postFilter, + * 1->postFilter. + * + * @note Methods are not declared abstract as it is perfectly legitimate + * for an implementation not to want anything to happen on a step + */ + +class HTMLPurifier_Filter +{ + + /** + * Name of the filter for identification purposes. + * @type string + */ + public $name; + + /** + * Pre-processor function, handles HTML before HTML Purifier + * @param string $html + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function preFilter($html, $config, $context) + { + return $html; + } + + /** + * Post-processor function, handles HTML after HTML Purifier + * @param string $html + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function postFilter($html, $config, $context) + { + return $html; + } +} + +// vim: et sw=4 sts=4 diff --git a/tools/htmlpurifier/standalone/HTMLPurifier/Filter/ExtractStyleBlocks.php b/tools/htmlpurifier/HTMLPurifier/Filter/ExtractStyleBlocks.php similarity index 97% rename from tools/htmlpurifier/standalone/HTMLPurifier/Filter/ExtractStyleBlocks.php rename to tools/htmlpurifier/HTMLPurifier/Filter/ExtractStyleBlocks.php index a59935c39..66f70b0fc 100644 --- a/tools/htmlpurifier/standalone/HTMLPurifier/Filter/ExtractStyleBlocks.php +++ b/tools/htmlpurifier/HTMLPurifier/Filter/ExtractStyleBlocks.php @@ -95,7 +95,10 @@ class HTMLPurifier_Filter_ExtractStyleBlocks extends HTMLPurifier_Filter if ($tidy !== null) { $this->_tidy = $tidy; } - $html = preg_replace_callback('#(.+)#isU', array($this, 'styleCallback'), $html); + // NB: this must be NON-greedy because if we have + // + // we must not grab foo + + + +

Smarty {Smarty::SMARTY_VERSION} Debug Console + - {if isset($template_name)}{$template_name|debug_print_var nofilter} {/if}{if !empty($template_data)}Total Time {$execution_time|string_format:"%.5f"}{/if}

+ + {if !empty($template_data)} +

included templates & config files (load time in seconds)

+
+ {foreach $template_data as $template} + {$template.name} +
   + (compile {$template['compile_time']|string_format:"%.5f"}) (render {$template['render_time']|string_format:"%.5f"}) (cache {$template['cache_time']|string_format:"%.5f"}) + +
+ {/foreach} +
+ {/if} + +

assigned template variables

+ + + {foreach $assigned_vars as $vars} + + + + + {/foreach} +

${$vars@key}

+ {if isset($vars['nocache'])}Nocache
{/if} + {if isset($vars['scope'])}Origin: {$vars['scope']|debug_print_var nofilter}{/if} +

Value

{$vars['value']|debug_print_var:10:80 nofilter}
{if isset($vars['attributes'])}

Attributes

{$vars['attributes']|debug_print_var nofilter} {/if}
+ +

assigned config file variables

+ + + {foreach $config_vars as $vars} + + + + + {/foreach} + +

#{$vars@key}#

+ {if isset($vars['scope'])}Origin: {$vars['scope']|debug_print_var nofilter}{/if} +
{$vars['value']|debug_print_var:10:80 nofilter}
+ + +{/capture} + diff --git a/tools/smarty/index.php b/tools/smarty/index.php index aca71cfae..63bf35dd9 100644 --- a/tools/smarty/index.php +++ b/tools/smarty/index.php @@ -1,35 +1,29 @@ - -* @copyright 2007-2017 PrestaShop SA -* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) -* International Registered Trademark & Property of PrestaShop SA -*/ - -header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); -header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); - -header('Cache-Control: no-store, no-cache, must-revalidate'); -header('Cache-Control: post-check=0, pre-check=0', false); -header('Pragma: no-cache'); - -header('Location: ../../'); -exit; + +* @copyright 2010-2020 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); +header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); + +header('Cache-Control: no-store, no-cache, must-revalidate'); +header('Cache-Control: post-check=0, pre-check=0', false); +header('Pragma: no-cache'); + +header('Location: ../../'); +exit; diff --git a/tools/smarty/plugins/block.textformat.php b/tools/smarty/plugins/block.textformat.php index abf544939..5e494637e 100644 --- a/tools/smarty/plugins/block.textformat.php +++ b/tools/smarty/plugins/block.textformat.php @@ -5,22 +5,20 @@ * @package Smarty * @subpackage PluginsBlock */ - /** * Smarty {textformat}{/textformat} block plugin - * Type: block function
- * Name: textformat
+ * Type: block function + * Name: textformat * Purpose: format text a certain way with preset styles - * or custom wrap/indent settings
+ * or custom wrap/indent settings * Params: - *
+ *
  * - style         - string (email)
  * - indent        - integer (0)
  * - wrap          - integer (80)
  * - wrap_char     - string ("\n")
  * - indent_char   - string (" ")
  * - wrap_boundary - boolean (true)
- * 
* * @link http://www.smarty.net/manual/en/language.function.textformat.php {textformat} * (Smarty online manual) @@ -32,13 +30,23 @@ * * @return string content re-formatted * @author Monte Ohrt + * @throws \SmartyException */ -function smarty_block_textformat($params, $content, $template, &$repeat) +function smarty_block_textformat($params, $content, Smarty_Internal_Template $template, &$repeat) { if (is_null($content)) { return; } - + if (Smarty::$_MBSTRING) { + $template->_checkPlugins( + array( + array( + 'function' => 'smarty_modifier_mb_wordwrap', + 'file' => SMARTY_PLUGINS_DIR . 'modifier.mb_wordwrap.php' + ) + ) + ); + } $style = null; $indent = 0; $indent_first = 0; @@ -47,51 +55,55 @@ function smarty_block_textformat($params, $content, $template, &$repeat) $wrap_char = "\n"; $wrap_cut = false; $assign = null; - foreach ($params as $_key => $_val) { switch ($_key) { case 'style': case 'indent_char': case 'wrap_char': case 'assign': - $$_key = (string) $_val; + $$_key = (string)$_val; break; - case 'indent': case 'indent_first': case 'wrap': - $$_key = (int) $_val; + $$_key = (int)$_val; break; - case 'wrap_cut': - $$_key = (bool) $_val; + $$_key = (bool)$_val; break; - default: - trigger_error("textformat: unknown attribute '$_key'"); + trigger_error("textformat: unknown attribute '{$_key}'"); } } - - if ($style == 'email') { + if ($style === 'email') { $wrap = 72; } // split into paragraphs $_paragraphs = preg_split('![\r\n]{2}!', $content); - foreach ($_paragraphs as &$_paragraph) { if (!$_paragraph) { continue; } // convert mult. spaces & special chars to single space - $_paragraph = preg_replace(array('!\s+!' . Smarty::$_UTF8_MODIFIER, '!(^\s+)|(\s+$)!' . Smarty::$_UTF8_MODIFIER), array(' ', ''), $_paragraph); + $_paragraph = + preg_replace( + array( + '!\s+!' . Smarty::$_UTF8_MODIFIER, + '!(^\s+)|(\s+$)!' . Smarty::$_UTF8_MODIFIER + ), + array( + ' ', + '' + ), + $_paragraph + ); // indent first line if ($indent_first > 0) { $_paragraph = str_repeat($indent_char, $indent_first) . $_paragraph; } // wordwrap sentences if (Smarty::$_MBSTRING) { - require_once(SMARTY_PLUGINS_DIR . 'shared.mb_wordwrap.php'); - $_paragraph = smarty_mb_wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut); + $_paragraph = smarty_modifier_mb_wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut); } else { $_paragraph = wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut); } @@ -101,7 +113,6 @@ function smarty_block_textformat($params, $content, $template, &$repeat) } } $_output = implode($wrap_char . $wrap_char, $_paragraphs); - if ($assign) { $template->assign($assign, $_output); } else { diff --git a/tools/smarty/plugins/function.counter.php b/tools/smarty/plugins/function.counter.php index 4da85a14e..a4129e77c 100644 --- a/tools/smarty/plugins/function.counter.php +++ b/tools/smarty/plugins/function.counter.php @@ -5,11 +5,10 @@ * @package Smarty * @subpackage PluginsFunction */ - /** * Smarty {counter} function plugin - * Type: function
- * Name: counter
+ * Type: function + * Name: counter * Purpose: print out a counter value * * @author Monte Ohrt @@ -24,55 +23,40 @@ function smarty_function_counter($params, $template) { static $counters = array(); - - $name = (isset($params['name'])) ? $params['name'] : 'default'; - if (!isset($counters[$name])) { - $counters[$name] = array( - 'start' => 1, - 'skip' => 1, - 'direction' => 'up', - 'count' => 1 - ); + $name = (isset($params[ 'name' ])) ? $params[ 'name' ] : 'default'; + if (!isset($counters[ $name ])) { + $counters[ $name ] = array('start' => 1, 'skip' => 1, 'direction' => 'up', 'count' => 1); } - $counter =& $counters[$name]; - - if (isset($params['start'])) { - $counter['start'] = $counter['count'] = (int) $params['start']; + $counter =& $counters[ $name ]; + if (isset($params[ 'start' ])) { + $counter[ 'start' ] = $counter[ 'count' ] = (int)$params[ 'start' ]; } - - if (!empty($params['assign'])) { - $counter['assign'] = $params['assign']; + if (!empty($params[ 'assign' ])) { + $counter[ 'assign' ] = $params[ 'assign' ]; } - - if (isset($counter['assign'])) { - $template->assign($counter['assign'], $counter['count']); + if (isset($counter[ 'assign' ])) { + $template->assign($counter[ 'assign' ], $counter[ 'count' ]); } - - if (isset($params['print'])) { - $print = (bool) $params['print']; + if (isset($params[ 'print' ])) { + $print = (bool)$params[ 'print' ]; } else { - $print = empty($counter['assign']); + $print = empty($counter[ 'assign' ]); } - if ($print) { - $retval = $counter['count']; + $retval = $counter[ 'count' ]; } else { $retval = null; } - - if (isset($params['skip'])) { - $counter['skip'] = $params['skip']; + if (isset($params[ 'skip' ])) { + $counter[ 'skip' ] = $params[ 'skip' ]; } - - if (isset($params['direction'])) { - $counter['direction'] = $params['direction']; + if (isset($params[ 'direction' ])) { + $counter[ 'direction' ] = $params[ 'direction' ]; } - - if ($counter['direction'] == "down") { - $counter['count'] -= $counter['skip']; + if ($counter[ 'direction' ] === 'down') { + $counter[ 'count' ] -= $counter[ 'skip' ]; } else { - $counter['count'] += $counter['skip']; + $counter[ 'count' ] += $counter[ 'skip' ]; } - return $retval; } diff --git a/tools/smarty/plugins/function.cycle.php b/tools/smarty/plugins/function.cycle.php index 8dc5cd9d5..07ffcc5e2 100644 --- a/tools/smarty/plugins/function.cycle.php +++ b/tools/smarty/plugins/function.cycle.php @@ -5,15 +5,14 @@ * @package Smarty * @subpackage PluginsFunction */ - /** * Smarty {cycle} function plugin - * Type: function
- * Name: cycle
- * Date: May 3, 2002
- * Purpose: cycle through given values
+ * Type: function + * Name: cycle + * Date: May 3, 2002 + * Purpose: cycle through given values * Params: - *
+ *
  * - name      - name of cycle (optional)
  * - values    - comma separated list of values to cycle, or an array of values to cycle
  *               (this can be left out for subsequent calls)
@@ -22,86 +21,72 @@
  * - advance   - boolean - whether or not to advance the cycle
  * - delimiter - the value delimiter, default is ","
  * - assign    - boolean, assigns to template var instead of printed.
- * 
- * Examples:
- *
+ *
+ * Examples:
+ *
  * {cycle values="#eeeeee,#d0d0d0d"}
  * {cycle name=row values="one,two,three" reset=true}
  * {cycle name=row}
- * 
* - * @link http://www.smarty.net/manual/en/language.function.cycle.php {cycle} + * @link http://www.smarty.net/manual/en/language.function.cycle.php {cycle} * (Smarty online manual) - * @author Monte Ohrt - * @author credit to Mark Priatel - * @author credit to Gerard - * @author credit to Jason Sweat - * @version 1.3 + * @author Monte Ohrt + * @author credit to Mark Priatel + * @author credit to Gerard + * @author credit to Jason Sweat + * @version 1.3 * * @param array $params parameters * @param Smarty_Internal_Template $template template object * * @return string|null */ - function smarty_function_cycle($params, $template) { static $cycle_vars; - - $name = (empty($params['name'])) ? 'default' : $params['name']; - $print = (isset($params['print'])) ? (bool) $params['print'] : true; - $advance = (isset($params['advance'])) ? (bool) $params['advance'] : true; - $reset = (isset($params['reset'])) ? (bool) $params['reset'] : false; - - if (!isset($params['values'])) { - if (!isset($cycle_vars[$name]['values'])) { - trigger_error("cycle: missing 'values' parameter"); - + $name = (empty($params[ 'name' ])) ? 'default' : $params[ 'name' ]; + $print = (isset($params[ 'print' ])) ? (bool)$params[ 'print' ] : true; + $advance = (isset($params[ 'advance' ])) ? (bool)$params[ 'advance' ] : true; + $reset = (isset($params[ 'reset' ])) ? (bool)$params[ 'reset' ] : false; + if (!isset($params[ 'values' ])) { + if (!isset($cycle_vars[ $name ][ 'values' ])) { + trigger_error('cycle: missing \'values\' parameter'); return; } } else { - if (isset($cycle_vars[$name]['values']) - && $cycle_vars[$name]['values'] != $params['values'] - ) { - $cycle_vars[$name]['index'] = 0; + if (isset($cycle_vars[ $name ][ 'values' ]) && $cycle_vars[ $name ][ 'values' ] !== $params[ 'values' ]) { + $cycle_vars[ $name ][ 'index' ] = 0; } - $cycle_vars[$name]['values'] = $params['values']; + $cycle_vars[ $name ][ 'values' ] = $params[ 'values' ]; } - - if (isset($params['delimiter'])) { - $cycle_vars[$name]['delimiter'] = $params['delimiter']; - } elseif (!isset($cycle_vars[$name]['delimiter'])) { - $cycle_vars[$name]['delimiter'] = ','; + if (isset($params[ 'delimiter' ])) { + $cycle_vars[ $name ][ 'delimiter' ] = $params[ 'delimiter' ]; + } elseif (!isset($cycle_vars[ $name ][ 'delimiter' ])) { + $cycle_vars[ $name ][ 'delimiter' ] = ','; } - - if (is_array($cycle_vars[$name]['values'])) { - $cycle_array = $cycle_vars[$name]['values']; + if (is_array($cycle_vars[ $name ][ 'values' ])) { + $cycle_array = $cycle_vars[ $name ][ 'values' ]; } else { - $cycle_array = explode($cycle_vars[$name]['delimiter'], $cycle_vars[$name]['values']); + $cycle_array = explode($cycle_vars[ $name ][ 'delimiter' ], $cycle_vars[ $name ][ 'values' ]); } - - if (!isset($cycle_vars[$name]['index']) || $reset) { - $cycle_vars[$name]['index'] = 0; + if (!isset($cycle_vars[ $name ][ 'index' ]) || $reset) { + $cycle_vars[ $name ][ 'index' ] = 0; } - - if (isset($params['assign'])) { + if (isset($params[ 'assign' ])) { $print = false; - $template->assign($params['assign'], $cycle_array[$cycle_vars[$name]['index']]); + $template->assign($params[ 'assign' ], $cycle_array[ $cycle_vars[ $name ][ 'index' ] ]); } - if ($print) { - $retval = $cycle_array[$cycle_vars[$name]['index']]; + $retval = $cycle_array[ $cycle_vars[ $name ][ 'index' ] ]; } else { $retval = null; } - if ($advance) { - if ($cycle_vars[$name]['index'] >= count($cycle_array) - 1) { - $cycle_vars[$name]['index'] = 0; + if ($cycle_vars[ $name ][ 'index' ] >= count($cycle_array) - 1) { + $cycle_vars[ $name ][ 'index' ] = 0; } else { - $cycle_vars[$name]['index'] ++; + $cycle_vars[ $name ][ 'index' ]++; } } - return $retval; } diff --git a/tools/smarty/plugins/function.fetch.php b/tools/smarty/plugins/function.fetch.php index 3506d4a8d..768761b23 100644 --- a/tools/smarty/plugins/function.fetch.php +++ b/tools/smarty/plugins/function.fetch.php @@ -5,11 +5,10 @@ * @package Smarty * @subpackage PluginsFunction */ - /** * Smarty {fetch} plugin - * Type: function
- * Name: fetch
+ * Type: function + * Name: fetch * Purpose: fetch file, web or ftp data and display results * * @link http://www.smarty.net/manual/en/language.function.fetch.php {fetch} @@ -24,129 +23,120 @@ */ function smarty_function_fetch($params, $template) { - if (empty($params['file'])) { - trigger_error("[plugin] fetch parameter 'file' cannot be empty", E_USER_NOTICE); - + if (empty($params[ 'file' ])) { + trigger_error('[plugin] fetch parameter \'file\' cannot be empty', E_USER_NOTICE); return; } - // strip file protocol - if (stripos($params['file'], 'file://') === 0) { - $params['file'] = substr($params['file'], 7); + if (stripos($params[ 'file' ], 'file://') === 0) { + $params[ 'file' ] = substr($params[ 'file' ], 7); } - - $protocol = strpos($params['file'], '://'); + $protocol = strpos($params[ 'file' ], '://'); if ($protocol !== false) { - $protocol = strtolower(substr($params['file'], 0, $protocol)); + $protocol = strtolower(substr($params[ 'file' ], 0, $protocol)); } - if (isset($template->smarty->security_policy)) { if ($protocol) { // remote resource (or php stream, …) - if (!$template->smarty->security_policy->isTrustedUri($params['file'])) { + if (!$template->smarty->security_policy->isTrustedUri($params[ 'file' ])) { return; } } else { // local file - if (!$template->smarty->security_policy->isTrustedResourceDir($params['file'])) { + if (!$template->smarty->security_policy->isTrustedResourceDir($params[ 'file' ])) { return; } } } - $content = ''; - if ($protocol == 'http') { + if ($protocol === 'http') { // http fetch - if ($uri_parts = parse_url($params['file'])) { + if ($uri_parts = parse_url($params[ 'file' ])) { // set defaults - $host = $server_name = $uri_parts['host']; + $host = $server_name = $uri_parts[ 'host' ]; $timeout = 30; - $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"; - $agent = "Smarty Template Engine " . Smarty::SMARTY_VERSION; - $referer = ""; - $uri = !empty($uri_parts['path']) ? $uri_parts['path'] : '/'; - $uri .= !empty($uri_parts['query']) ? '?' . $uri_parts['query'] : ''; + $accept = 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*'; + $agent = 'Smarty Template Engine ' . Smarty::SMARTY_VERSION; + $referer = ''; + $uri = !empty($uri_parts[ 'path' ]) ? $uri_parts[ 'path' ] : '/'; + $uri .= !empty($uri_parts[ 'query' ]) ? '?' . $uri_parts[ 'query' ] : ''; $_is_proxy = false; - if (empty($uri_parts['port'])) { + if (empty($uri_parts[ 'port' ])) { $port = 80; } else { - $port = $uri_parts['port']; + $port = $uri_parts[ 'port' ]; } - if (!empty($uri_parts['user'])) { - $user = $uri_parts['user']; + if (!empty($uri_parts[ 'user' ])) { + $user = $uri_parts[ 'user' ]; } - if (!empty($uri_parts['pass'])) { - $pass = $uri_parts['pass']; + if (!empty($uri_parts[ 'pass' ])) { + $pass = $uri_parts[ 'pass' ]; } // loop through parameters, setup headers foreach ($params as $param_key => $param_value) { switch ($param_key) { - case "file": - case "assign": - case "assign_headers": + case 'file': + case 'assign': + case 'assign_headers': break; - case "user": + case 'user': if (!empty($param_value)) { $user = $param_value; } break; - case "pass": + case 'pass': if (!empty($param_value)) { $pass = $param_value; } break; - case "accept": + case 'accept': if (!empty($param_value)) { $accept = $param_value; } break; - case "header": + case 'header': if (!empty($param_value)) { if (!preg_match('![\w\d-]+: .+!', $param_value)) { - trigger_error("[plugin] invalid header format '" . $param_value . "'", E_USER_NOTICE); - + trigger_error("[plugin] invalid header format '{$param_value}'", E_USER_NOTICE); return; } else { $extra_headers[] = $param_value; } } break; - case "proxy_host": + case 'proxy_host': if (!empty($param_value)) { $proxy_host = $param_value; } break; - case "proxy_port": + case 'proxy_port': if (!preg_match('!\D!', $param_value)) { - $proxy_port = (int) $param_value; + $proxy_port = (int)$param_value; } else { - trigger_error("[plugin] invalid value for attribute '" . $param_key . "'", E_USER_NOTICE); - + trigger_error("[plugin] invalid value for attribute '{$param_key }'", E_USER_NOTICE); return; } break; - case "agent": + case 'agent': if (!empty($param_value)) { $agent = $param_value; } break; - case "referer": + case 'referer': if (!empty($param_value)) { $referer = $param_value; } break; - case "timeout": + case 'timeout': if (!preg_match('!\D!', $param_value)) { - $timeout = (int) $param_value; + $timeout = (int)$param_value; } else { - trigger_error("[plugin] invalid value for attribute '" . $param_key . "'", E_USER_NOTICE); - + trigger_error("[plugin] invalid value for attribute '{$param_key}'", E_USER_NOTICE); return; } break; default: - trigger_error("[plugin] unrecognized attribute '" . $param_key . "'", E_USER_NOTICE); - + trigger_error("[plugin] unrecognized attribute '{$param_key}'", E_USER_NOTICE); return; } } @@ -156,14 +146,12 @@ function smarty_function_fetch($params, $template) } else { $fp = fsockopen($server_name, $port, $errno, $errstr, $timeout); } - if (!$fp) { trigger_error("[plugin] unable to fetch: $errstr ($errno)", E_USER_NOTICE); - return; } else { if ($_is_proxy) { - fputs($fp, 'GET ' . $params['file'] . " HTTP/1.0\r\n"); + fputs($fp, 'GET ' . $params[ 'file' ] . " HTTP/1.0\r\n"); } else { fputs($fp, "GET $uri HTTP/1.0\r\n"); } @@ -185,36 +173,31 @@ function smarty_function_fetch($params, $template) } } if (!empty($user) && !empty($pass)) { - fputs($fp, "Authorization: BASIC " . base64_encode("$user:$pass") . "\r\n"); + fputs($fp, 'Authorization: BASIC ' . base64_encode("$user:$pass") . "\r\n"); } - fputs($fp, "\r\n"); while (!feof($fp)) { $content .= fgets($fp, 4096); } fclose($fp); $csplit = preg_split("!\r\n\r\n!", $content, 2); - - $content = $csplit[1]; - - if (!empty($params['assign_headers'])) { - $template->assign($params['assign_headers'], preg_split("!\r\n!", $csplit[0])); + $content = $csplit[ 1 ]; + if (!empty($params[ 'assign_headers' ])) { + $template->assign($params[ 'assign_headers' ], preg_split("!\r\n!", $csplit[ 0 ])); } } } else { trigger_error("[plugin fetch] unable to parse URL, check syntax", E_USER_NOTICE); - return; } } else { - $content = @file_get_contents($params['file']); + $content = @file_get_contents($params[ 'file' ]); if ($content === false) { - throw new SmartyException("{fetch} cannot read resource '" . $params['file'] . "'"); + throw new SmartyException("{fetch} cannot read resource '" . $params[ 'file' ] . "'"); } } - - if (!empty($params['assign'])) { - $template->assign($params['assign'], $content); + if (!empty($params[ 'assign' ])) { + $template->assign($params[ 'assign' ], $content); } else { return $content; } diff --git a/tools/smarty/plugins/function.html_checkboxes.php b/tools/smarty/plugins/function.html_checkboxes.php index d78680368..302358edd 100644 --- a/tools/smarty/plugins/function.html_checkboxes.php +++ b/tools/smarty/plugins/function.html_checkboxes.php @@ -5,22 +5,21 @@ * @package Smarty * @subpackage PluginsFunction */ - /** * Smarty {html_checkboxes} function plugin - * File: function.html_checkboxes.php
- * Type: function
- * Name: html_checkboxes
- * Date: 24.Feb.2003
- * Purpose: Prints out a list of checkbox input types
+ * File: function.html_checkboxes.php + * Type: function + * Name: html_checkboxes + * Date: 24.Feb.2003 + * Purpose: Prints out a list of checkbox input types * Examples: - *
+ *
  * {html_checkboxes values=$ids output=$names}
  * {html_checkboxes values=$ids name='box' separator='
' output=$names} * {html_checkboxes values=$ids checked=$checked separator='
' output=$names} - *
+ * * Params: - *
+ *
  * - name       (optional) - string default "checkbox"
  * - values     (required) - array
  * - options    (optional) - associative array
@@ -29,24 +28,30 @@
  * - output     (optional) - the output next to each checkbox
  * - assign     (optional) - assign the output as an array to this variable
  * - escape     (optional) - escape the content (not value), defaults to true
- * 
* - * @link http://www.smarty.net/manual/en/language.function.html.checkboxes.php {html_checkboxes} + * @link http://www.smarty.net/manual/en/language.function.html.checkboxes.php {html_checkboxes} * (Smarty online manual) - * @author Christopher Kvarme - * @author credits to Monte Ohrt - * @version 1.0 + * @author Christopher Kvarme + * @author credits to Monte Ohrt + * @version 1.0 * - * @param array $params parameters - * @param object $template template object + * @param array $params parameters + * @param Smarty_Internal_Template $template template object * * @return string - * @uses smarty_function_escape_special_chars() + * @uses smarty_function_escape_special_chars() + * @throws \SmartyException */ -function smarty_function_html_checkboxes($params, $template) +function smarty_function_html_checkboxes($params, Smarty_Internal_Template $template) { - require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'); - + $template->_checkPlugins( + array( + array( + 'function' => 'smarty_function_escape_special_chars', + 'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php' + ) + ) + ); $name = 'checkbox'; $values = null; $options = null; @@ -56,182 +61,226 @@ function smarty_function_html_checkboxes($params, $template) $labels = true; $label_ids = false; $output = null; - $extra = ''; - foreach ($params as $_key => $_val) { switch ($_key) { case 'name': case 'separator': - $$_key = (string) $_val; + $$_key = (string)$_val; break; - case 'escape': case 'labels': case 'label_ids': - $$_key = (bool) $_val; + $$_key = (bool)$_val; break; - case 'options': - $$_key = (array) $_val; + $$_key = (array)$_val; break; - case 'values': case 'output': - $$_key = array_values((array) $_val); + $$_key = array_values((array)$_val); break; - case 'checked': case 'selected': if (is_array($_val)) { $selected = array(); foreach ($_val as $_sel) { if (is_object($_sel)) { - if (method_exists($_sel, "__toString")) { - $_sel = smarty_function_escape_special_chars((string) $_sel->__toString()); + if (method_exists($_sel, '__toString')) { + $_sel = smarty_function_escape_special_chars((string)$_sel->__toString()); } else { - trigger_error("html_checkboxes: selected attribute contains an object of class '" . get_class($_sel) . "' without __toString() method", E_USER_NOTICE); + trigger_error( + 'html_checkboxes: selected attribute contains an object of class \'' . + get_class($_sel) . '\' without __toString() method', + E_USER_NOTICE + ); continue; } } else { - $_sel = smarty_function_escape_special_chars((string) $_sel); + $_sel = smarty_function_escape_special_chars((string)$_sel); } - $selected[$_sel] = true; + $selected[ $_sel ] = true; } } elseif (is_object($_val)) { - if (method_exists($_val, "__toString")) { - $selected = smarty_function_escape_special_chars((string) $_val->__toString()); + if (method_exists($_val, '__toString')) { + $selected = smarty_function_escape_special_chars((string)$_val->__toString()); } else { - trigger_error("html_checkboxes: selected attribute is an object of class '" . get_class($_val) . "' without __toString() method", E_USER_NOTICE); + trigger_error( + 'html_checkboxes: selected attribute is an object of class \'' . get_class($_val) . + '\' without __toString() method', + E_USER_NOTICE + ); } } else { - $selected = smarty_function_escape_special_chars((string) $_val); + $selected = smarty_function_escape_special_chars((string)$_val); } break; - case 'checkboxes': - trigger_error('html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead', E_USER_WARNING); - $options = (array) $_val; + trigger_error( + 'html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead', + E_USER_WARNING + ); + $options = (array)$_val; break; - case 'assign': break; - case 'strict': break; - case 'disabled': case 'readonly': - if (!empty($params['strict'])) { + if (!empty($params[ 'strict' ])) { if (!is_scalar($_val)) { - trigger_error("html_options: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute", E_USER_NOTICE); + trigger_error( + "html_options: {$_key} attribute must be a scalar, only boolean true or string '{$_key}' will actually add the attribute", + E_USER_NOTICE + ); } - if ($_val === true || $_val === $_key) { $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"'; } - break; } // omit break; to fall through! - + // no break default: if (!is_array($_val)) { $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"'; } else { - trigger_error("html_checkboxes: extra attribute '$_key' cannot be an array", E_USER_NOTICE); + trigger_error("html_checkboxes: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE); } break; } } - if (!isset($options) && !isset($values)) { return ''; } /* raise error here? */ - $_html_result = array(); - if (isset($options)) { foreach ($options as $_key => $_val) { - $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids, $escape); + $_html_result[] = + smarty_function_html_checkboxes_output( + $name, + $_key, + $_val, + $selected, + $extra, + $separator, + $labels, + $label_ids, + $escape + ); } } else { foreach ($values as $_i => $_key) { - $_val = isset($output[$_i]) ? $output[$_i] : ''; - $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids, $escape); + $_val = isset($output[ $_i ]) ? $output[ $_i ] : ''; + $_html_result[] = + smarty_function_html_checkboxes_output( + $name, + $_key, + $_val, + $selected, + $extra, + $separator, + $labels, + $label_ids, + $escape + ); } } - - if (!empty($params['assign'])) { - $template->assign($params['assign'], $_html_result); + if (!empty($params[ 'assign' ])) { + $template->assign($params[ 'assign' ], $_html_result); } else { return implode("\n", $_html_result); } } -function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids, $escape = true) -{ +/** + * @param $name + * @param $value + * @param $output + * @param $selected + * @param $extra + * @param $separator + * @param $labels + * @param $label_ids + * @param bool $escape + * + * @return string + */ +function smarty_function_html_checkboxes_output( + $name, + $value, + $output, + $selected, + $extra, + $separator, + $labels, + $label_ids, + $escape = true +) { $_output = ''; - if (is_object($value)) { - if (method_exists($value, "__toString")) { - $value = (string) $value->__toString(); + if (method_exists($value, '__toString')) { + $value = (string)$value->__toString(); } else { - trigger_error("html_options: value is an object of class '" . get_class($value) . "' without __toString() method", E_USER_NOTICE); - + trigger_error( + 'html_options: value is an object of class \'' . get_class($value) . + '\' without __toString() method', + E_USER_NOTICE + ); return ''; } } else { - $value = (string) $value; + $value = (string)$value; } - if (is_object($output)) { - if (method_exists($output, "__toString")) { - $output = (string) $output->__toString(); + if (method_exists($output, '__toString')) { + $output = (string)$output->__toString(); } else { - trigger_error("html_options: output is an object of class '" . get_class($output) . "' without __toString() method", E_USER_NOTICE); - + trigger_error( + 'html_options: output is an object of class \'' . get_class($output) . + '\' without __toString() method', + E_USER_NOTICE + ); return ''; } } else { - $output = (string) $output; + $output = (string)$output; } - if ($labels) { if ($label_ids) { - $_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_', $name . '_' . $value)); + $_id = smarty_function_escape_special_chars( + preg_replace( + '![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, + '_', + $name . '_' . $value + ) + ); $_output .= '