示例#1
1
function filter_xss($string)
{
    // Only operate on valid UTF-8 strings. This is necessary to prevent cross
    // site scripting issues on Internet Explorer 6.
    if (!validate_utf8($string)) {
        return '';
    }
    $allowed_tags = dPgetConfig('filter_allowed_tags', array('a', 'em', 'strong', 'cite', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'table', 'tr', 'td', 'tbody', 'thead', 'br', 'b', 'i'));
    // Store the input format
    _filter_xss_split($allowed_tags, TRUE);
    // Remove NUL characters (ignored by some browsers)
    $string = str_replace(chr(0), '', $string);
    // Remove Netscape 4 JS entities
    $string = preg_replace('%&\\s*\\{[^}]*(\\}\\s*;?|$)%', '', $string);
    // Defuse all HTML entities
    $string = str_replace('&', '&', $string);
    // Change back only well-formed entities in our whitelist
    // Decimal numeric entities
    $string = preg_replace('/&#([0-9]+;)/', '&#\\1', $string);
    // Hexadecimal numeric entities
    $string = preg_replace('/&#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\\1', $string);
    // Named entities
    $string = preg_replace('/&([A-Za-z][A-Za-z0-9]*;)/', '&\\1', $string);
    return preg_replace_callback('%
    (
    <(?=[^a-zA-Z!/])  # a lone <
    |                 # or
    <!--.*?-->        # a comment
    |                 # or
    <[^>]*(>|$)       # a string that starts with a <, up until the > or the end of the string
    |                 # or
    >                 # just a >
    )%x', '_filter_xss_split', $string);
}
示例#2
0
function multilang_filter($courseid, $text)
{
    global $CFG;
    // [pj] I don't know about you but I find this new implementation funny :P
    // [skodak] I was laughing while rewriting it ;-)
    // [nicolasconnault] Should support inverted attributes: <span class="multilang" lang="en"> (Doesn't work curently)
    // [skodak] it supports it now, though it is slower - any better idea?
    if (empty($text) or is_numeric($text)) {
        return $text;
    }
    if (empty($CFG->filter_multilang_force_old) and !empty($CFG->filter_multilang_converted)) {
        // new syntax
        $search = '/(<span(\\s+lang="[a-zA-Z0-9_-]+"|\\s+class="multilang"){2}\\s*>.*?<\\/span>)(\\s*<span(\\s+lang="[a-zA-Z0-9_-]+"|\\s+class="multilang"){2}\\s*>.*?<\\/span>)+/is';
    } else {
        // old syntax
        $search = '/(<(?:lang|span) lang="[a-zA-Z0-9_-]*".*?>.*?<\\/(?:lang|span)>)(\\s*<(?:lang|span) lang="[a-zA-Z0-9_-]*".*?>.*?<\\/(?:lang|span)>)+/is';
    }
    $result = preg_replace_callback($search, 'multilang_filter_impl', $text);
    if (is_null($result)) {
        return $text;
        //error during regex processing (too many nested spans?)
    } else {
        return $result;
    }
}
示例#3
0
 /**
  * Parses escape sequences in strings (all string types apart from single quoted).
  *
  * @param string      $str   String without quotes
  * @param null|string $quote Quote type
  *
  * @return string String with escape sequences parsed
  */
 public static function parseEscapeSequences($str, $quote)
 {
     if (null !== $quote) {
         $str = str_replace('\\' . $quote, $quote, $str);
     }
     return preg_replace_callback('~\\\\([\\\\$nrtfve]|[xX][0-9a-fA-F]{1,2}|[0-7]{1,3})~', array(__CLASS__, 'parseCallback'), $str);
 }
示例#4
0
function recurse($dir)
{
    echo "{$dir}\n";
    foreach (glob("{$dir}/*") as $filename) {
        if (is_dir($filename)) {
            recurse($filename);
        } elseif (eregi('\\.xml$', $filename)) {
            //~ echo "$filename\n";
            $file = file_get_contents($filename);
            $file = preg_replace_callback('~(<!\\[CDATA\\[)(.*)(\\]\\]>)~sU', "callback_htmlentities", $file);
            $file = preg_replace_callback('~(<!--)(.*)(-->)~sU', "callback_htmlentities", $file);
            // isn't in one function as it can match !CDATA[[...-->
            if ($GLOBALS["MODE"] == "escape") {
                $file = preg_replace_callback('~<(' . $GLOBALS['GOOD_TAGS'] . ')( [^>]*)?>(.*)</\\1>~sU', "callback_make_value", $file);
            } else {
                // "unescape"
                $file = str_replace("\r", "", $file);
                // for Windows version of Aspell
                $file = preg_replace_callback('~<(' . $GLOBALS['GOOD_TAGS'] . ')( [^>]*)? aspell="(.*)"/>~sU', "callback_make_contents", $file);
            }
            $fp = fopen($filename, "wb");
            fwrite($fp, $file);
            fclose($fp);
        }
    }
}
示例#5
0
function custom_permalinks($title)
{
    $title = sanitize_title_with_dashes($title);
    $toupper = create_function('$m', 'return strtoupper($m[0]);');
    $title = preg_replace_callback('/(%[0-9a-f]{2}?)+/', $toupper, $title);
    return $title;
}
示例#6
0
function axisFixer($string)
{
    $string = preg_replace_callback("/\\d+[\\d\\.]*/", "axisStrings", $string);
    $string = rangeFixer($string, "1");
    $string = preg_replace_callback("/\\d+[\\d\\.]*\\s+steps/", "axisSteps", $string);
    return $string;
}
示例#7
0
 /**
  * Filters all IE filters (AlphaImageLoader filter) through a callable.
  *
  * @param string   $content  The CSS
  * @param callable $callback A PHP callable
  *
  * @return string The filtered CSS
  */
 public static function filterIEFilters($content, $callback)
 {
     $pattern = static::REGEX_IE_FILTERS;
     return static::filterCommentless($content, function ($part) use(&$callback, $pattern) {
         return preg_replace_callback($pattern, $callback, $part);
     });
 }
示例#8
0
 protected function parse($st)
 {
     if (preg_replace_callback('#<tr>(.{1,100}нефтебаза.+?|.{1,200}[bg]>[АП]З[СК]?.+?)</tr>#su', function ($x) {
         if (strpos($x[1], 'нефтебаза')) {
             if (strpos($x[1], 'Туапсе')) {
                 $GLOBALS['operator'] = 'ОАО "Роснефть-Туапсенефтепродукт"';
             } else {
                 if ($this->region == 'RU-KDA') {
                     $GLOBALS['operator'] = 'ОАО "Роснефть-Кубаньнефтепродукт"';
                 } else {
                     $GLOBALS['operator'] = '';
                 }
             }
         }
         if (!preg_match('#' . "(?<ref>\\d+)" . '.+?/>(?<_addr>.+?)</td' . "#su", $x[0], $obj)) {
             return;
         }
         if (isset($GLOBALS['operator'])) {
             $obj['operator'] = $GLOBALS['operator'];
         }
         $obj['_addr'] = trim(strip_tags(str_replace('&nbsp;', ' ', $obj['_addr'])));
         $obj["fuel:octane_98"] = strpos($x[0], 'Аи-98') ? 'yes' : '';
         $obj["fuel:octane_95"] = strpos($x[0], 'Аи-95') ? 'yes' : '';
         $obj["fuel:octane_92"] = strpos($x[0], 'Аи-92') ? 'yes' : '';
         $obj["fuel:octane_80"] = strpos($x[0], 'Аи-80') ? 'yes' : '';
         $obj["fuel:diesel"] = strpos($x[0], 'ДТ') ? 'yes' : '';
         $this->addObject($this->makeObject($obj));
     }, $st)) {
     }
 }
示例#9
0
文件: ListTpl.php 项目: parsonsc/dofe
 private function ParseHeaderFooter($str, $uid = null)
 {
     $str = preg_replace_callback('/%sort_?link:([a-z0-9_]+)%/i', array(__CLASS__, 'GenSortlink'), $str);
     if (strpos($str, '%search_form%') !== false) {
         wpfb_loadclass('Output');
         $str = str_replace('%search_form%', WPFB_Output::GetSearchForm("", $_GET), $str);
     }
     $str = preg_replace_callback('/%print_?(script|style):([a-z0-9_-]+)%/i', array(__CLASS__, 'PrintScriptCallback'), $str);
     if (empty($uid)) {
         $uid = uniqid();
     }
     $str = str_replace('%uid%', $uid, $str);
     $count = 0;
     $str = preg_replace("/jQuery\\((.+?)\\)\\.dataTable\\s*\\((.*?)\\)(\\.?.*?)\\s*;/", 'jQuery($1).dataTable((function(options){/*%WPFB_DATA_TABLE_OPTIONS_FILTER%*/})($2))$3;', $str, -1, $count);
     if ($count > 0) {
         $dataTableOptions = array();
         list($sort_field, $sort_dir) = wpfb_call('Output', 'ParseSorting', $this->current_list->file_order);
         $file_tpl = WPFB_Core::GetTpls('file', $this->file_tpl_tag);
         if (($p = strpos($file_tpl, "%{$sort_field}%")) > 0) {
             // get the column index of field to sort
             $col_index = substr_count($file_tpl, "</t", 0, $p);
             $dataTableOptions["aaSorting"] = array(array($col_index, strtolower($sort_dir)));
         }
         if ($this->current_list->page_limit > 0) {
             $dataTableOptions["iDisplayLength"] = $this->current_list->page_limit;
         }
         $str = str_replace('/*%WPFB_DATA_TABLE_OPTIONS_FILTER%*/', " var wpfbOptions = " . json_encode($dataTableOptions) . "; " . " if('object' == typeof(options)) { for (var v in options) { wpfbOptions[v] = options[v]; } }" . " return wpfbOptions; ", $str);
     }
     return $str;
 }
示例#10
0
文件: Target.php 项目: hackyoung/leno
 public static function getFromRouter(Router $router)
 {
     $mode = $router->getMode();
     $parameters = [];
     $path = preg_replace_callback('/\\/\\${.*}/U', function ($matches) use(&$parameters) {
         $parameters[] = preg_replace('/\\/|\\$|\\{|\\}/', '', $matches[0]);
         return '';
     }, $router->getPath());
     $patharr = array_merge(explode('/', $router->getBase()), explode('/', $path));
     $path = array_filter(array_map(function ($p) {
         return \camelCase($p, true, '-');
     }, $patharr));
     if ($mode === Router::MOD_RESTFUL) {
         $request = $router->getRequest();
         $method = strtoupper($_POST['_method'] ?? $request->getMethod());
         $action = $router->getActionOfRestful($method);
         if ($action === null) {
             throw new \Leno\Http\Exception(501);
         }
     } else {
         $action = preg_replace_callback('/^[A-Z]/', function ($matches) {
             if (isset($matches[0])) {
                 return strtolower($matches[0]);
             }
         }, preg_replace('/\\..*$/', '', array_pop($path)));
     }
     try {
         return (new self(implode('\\', $path) . 'Controller'))->setMethod($action)->setParameters($parameters);
     } catch (\Exception $ex) {
         logger()->err((string) $ex);
         throw new \Leno\Http\Exception(404);
     }
 }
 /**
  * Here we do the work
  */
 public function execute($comment)
 {
     global $_CONF, $_TABLES, $_USER, $LANG_SX00;
     if (isset($_USER['uid']) && $_USER['uid'] > 1) {
         $uid = $_USER['uid'];
     } else {
         $uid = 1;
     }
     /**
      * Include Blacklist Data
      */
     $result = DB_query("SELECT value FROM {$_TABLES['spamx']} WHERE name='Personal'", 1);
     $nrows = DB_numRows($result);
     // named entities
     $comment = html_entity_decode($comment);
     // decimal notation
     $comment = preg_replace_callback('/&#(\\d+);/m', array($this, 'callbackDecimal'), $comment);
     // hex notation
     $comment = preg_replace_callback('/&#x([a-f0-9]+);/mi', array($this, 'callbackHex'), $comment);
     $ans = 0;
     for ($i = 1; $i <= $nrows; $i++) {
         list($val) = DB_fetchArray($result);
         $val = str_replace('#', '\\#', $val);
         if (preg_match("#{$val}#i", $comment)) {
             $ans = 1;
             // quit on first positive match
             SPAMX_log($LANG_SX00['foundspam'] . $val . $LANG_SX00['foundspam2'] . $uid . $LANG_SX00['foundspam3'] . $_SERVER['REMOTE_ADDR']);
             break;
         }
     }
     return $ans;
 }
示例#12
0
 public static function formatMessage(Rule $rule, $withValue = TRUE)
 {
     $message = $rule->message;
     if ($message instanceof Nette\Utils\Html) {
         return $message;
     } elseif ($message === NULL && is_string($rule->validator) && isset(static::$messages[$rule->validator])) {
         $message = static::$messages[$rule->validator];
     } elseif ($message == NULL) {
         // intentionally ==
         trigger_error("Missing validation message for control '{$rule->control->getName()}'.", E_USER_WARNING);
     }
     if ($translator = $rule->control->getForm()->getTranslator()) {
         $message = $translator->translate($message, is_int($rule->arg) ? $rule->arg : NULL);
     }
     $message = preg_replace_callback('#%(name|label|value|\\d+\\$[ds]|[ds])#', function ($m) use($rule, $withValue) {
         static $i = -1;
         switch ($m[1]) {
             case 'name':
                 return $rule->control->getName();
             case 'label':
                 return $rule->control->translate($rule->control->caption);
             case 'value':
                 return $withValue ? $rule->control->getValue() : $m[0];
             default:
                 $args = is_array($rule->arg) ? $rule->arg : array($rule->arg);
                 $i = (int) $m[1] ? $m[1] - 1 : $i + 1;
                 return isset($args[$i]) ? $args[$i] instanceof IControl ? $withValue ? $args[$i]->getValue() : "%{$i}" : $args[$i] : '';
         }
     }, $message);
     return $message;
 }
示例#13
0
 /** Builds the HTML code to be exported starting from what has been saved in DB
  * @param string $text
  * @return string
  */
 public function export($text)
 {
     $text = preg_replace_callback('/{CCM:CID_([0-9]+)}/i', array('ContentExporter', 'replacePageWithPlaceHolderInMatch'), $text);
     $text = preg_replace_callback('/{CCM:FID_([0-9]+)}/i', array('ContentExporter', 'replaceImageWithPlaceHolderInMatch'), $text);
     $text = preg_replace_callback('/{CCM:FID_DL_([0-9]+)}/i', array('ContentExporter', 'replaceFileWithPlaceHolderInMatch'), $text);
     return $text;
 }
示例#14
0
文件: string.php 项目: staabm/redaxo
 /**
  * Splits a string by spaces
  * (Strings with quotes will be regarded).
  *
  * Examples:
  * "a b 'c d'"   -> array('a', 'b', 'c d')
  * "a=1 b='c d'" -> array('a' => 1, 'b' => 'c d')
  *
  * @param string $string
  *
  * @return array
  */
 public static function split($string)
 {
     $string = trim($string);
     if (empty($string)) {
         return [];
     }
     $result = [];
     $spacer = '@@@REX_SPACER@@@';
     $quoted = [];
     $pattern = '@(["\'])((?:.*[^\\\\])?(?:\\\\\\\\)*)\\1@Us';
     $callback = function ($match) use($spacer, &$quoted) {
         $quoted[] = str_replace(['\\' . $match[1], '\\\\'], [$match[1], '\\'], $match[2]);
         return $spacer;
     };
     $string = preg_replace_callback($pattern, $callback, $string);
     $parts = preg_split('@\\s+@', $string);
     $i = 0;
     foreach ($parts as $part) {
         $part = explode('=', $part, 2);
         if (isset($part[1])) {
             $value = $part[1] == $spacer ? $quoted[$i++] : $part[1];
             $result[$part[0]] = $value;
         } else {
             $value = $part[0] == $spacer ? $quoted[$i++] : $part[0];
             $result[] = $value;
         }
     }
     return $result;
 }
示例#15
0
 /**
  * Turns an event into a method name, by replacing . and _ with a capital of the following word. For example,
  * if the event is something like user.updating, then the method would become userUpdating.
  *
  * @param string $event
  * @return string
  */
 protected static function eventMethod($event)
 {
     $callback = function ($matches) {
         return strtoupper($matches[1][1]);
     };
     return preg_replace_callback('/([._-][a-z])/i', $callback, $event);
 }
示例#16
0
文件: Str.php 项目: imjerrybao/phpbu
 /**
  * Date placeholder replacement.
  * Replaces %{somevalue} with date({somevalue}).
  *
  * @param  string               $string
  * @param  mixed <integer|null> $time
  * @return string
  */
 public static function replaceDatePlaceholders($string, $time = null)
 {
     $time = $time === null ? time() : $time;
     return preg_replace_callback('#%([a-zA-Z])#', function ($match) use($time) {
         return date($match[1], $time);
     }, $string);
 }
示例#17
0
 /**
  * 得到完整的数据表名
  * 
  * @access public
  * @return string
  */
 public function getTableName()
 {
     if (empty($this->trueTableName)) {
         $tableName = '';
         foreach ($this->viewFields as $key => $view) {
             // 获取数据表名称
             if (isset($view['_table'])) {
                 // 2011/10/17 添加实际表名定义支持 可以实现同一个表的视图
                 $tableName .= $view['_table'];
                 $prefix = $this->tablePrefix;
                 $tableName = preg_replace_callback("/__([A-Z_-]+)__/sU", function ($match) use($prefix) {
                     return $prefix . strtolower($match[1]);
                 }, $tableName);
             } else {
                 $class = $key . 'Model';
                 $Model = class_exists($class) ? new $class() : M($key);
                 $tableName .= $Model->getTableName();
             }
             // 表别名定义
             $tableName .= !empty($view['_as']) ? ' ' . $view['_as'] : ' ' . $key;
             // 支持ON 条件定义
             $tableName .= !empty($view['_on']) ? ' ON ' . $view['_on'] : '';
             // 指定JOIN类型 例如 RIGHT INNER LEFT 下一个表有效
             $type = !empty($view['_type']) ? $view['_type'] : '';
             $tableName .= ' ' . strtoupper($type) . ' JOIN ';
             $len = strlen($type . '_JOIN ');
         }
         $tableName = substr($tableName, 0, -$len);
         $this->trueTableName = $tableName;
     }
     return $this->trueTableName;
 }
示例#18
0
 public static function formatHtml($mask)
 {
     $args = func_get_args();
     return preg_replace_callback('#%#', function () use(&$args, &$count) {
         return htmlspecialchars($args[++$count], ENT_IGNORE | ENT_QUOTES, 'UTF-8');
     }, $mask);
 }
 private function _getContent($file)
 {
     $file = realpath($file);
     if (!$file || in_array($file, self::$filesIncluded) || false === ($content = @file_get_contents($file))) {
         // file missing, already included, or failed read
         return '';
     }
     self::$filesIncluded[] = realpath($file);
     $this->_currentDir = dirname($file);
     // remove UTF-8 BOM if present
     if (pack("CCC", 0xef, 0xbb, 0xbf) === substr($content, 0, 3)) {
         $content = substr($content, 3);
     }
     // ensure uniform EOLs
     $content = str_replace("\r\n", "\n", $content);
     // process @imports
     $content = preg_replace_callback('/
             @import\\s+
             (?:url\\(\\s*)?      # maybe url(
             [\'"]?               # maybe quote
             (.*?)                # 1 = URI
             [\'"]?               # maybe end quote
             (?:\\s*\\))?         # maybe )
             ([a-zA-Z,\\s]*)?     # 2 = media list
             ;                    # end token
         /x', array($this, '_importCB'), $content);
     if (self::$_isCss) {
         // rewrite remaining relative URIs
         $content = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/', array($this, '_urlCB'), $content);
     }
     return $this->_importedContent . $content;
 }
示例#20
0
 /**
  * formats the input using the singleTag/closeTag/openTag functions
  *
  * It is auto indenting the whole code, excluding <textarea>, <code> and <pre> tags that must be kept intact.
  * Those tags must however contain only htmlentities-escaped text for everything to work properly.
  * Inline tags are presented on a single line with their content
  *
  * @param Dwoo $dwoo the dwoo instance rendering this
  * @param string $input the xhtml to format
  * @return string formatted xhtml
  */
 public function process($input)
 {
     self::$tabCount = -1;
     // auto indent all but textareas & pre (or we have weird tabs inside)
     $input = preg_replace_callback("#(<[^>]+>)(\\s*)([^<]*)#", array('self', 'tagDispatcher'), $input);
     return $input;
 }
 public function format($message)
 {
     $message = preg_replace('/<info>(.*),\\s*(.*)<\\/info>/i', '<info>$2 ($1)</info>', $message);
     $formatted = parent::format($message);
     $clearEscapeCodes = '(?:39|49|0|22|24|25|27|28)';
     return preg_replace_callback("{\\[([0-9;]+)m(.*?)\\[(?:" . $clearEscapeCodes . ";)*?" . $clearEscapeCodes . "m}s", array($this, 'formatHtml'), $formatted);
 }
 /**
  * Format package name to CamelCase
  */
 public function inflectPackageVars($vars)
 {
     $vars['name'] = preg_replace_callback('/(?:^|_|-)(.?)/', function ($matches) {
         return strtoupper($matches[1]);
     }, $vars['name']);
     return $vars;
 }
 /**
  * {@inheritdoc}
  */
 public function process($text, $langcode)
 {
     $result = new FilterProcessResult($text);
     // Track if widget has been found so that we can attached the
     // jquery_ui_filter library and settings.
     $has_widget = FALSE;
     foreach (self::$widgets as $name => $widget) {
         if (strpos($text, '[' . $name) === FALSE) {
             continue;
         }
         $has_widget = TRUE;
         // Remove block tags around tokens.
         $text = preg_replace('#<(p|div)[^>]*>\\s*(\\[/?' . $name . '[^]]*\\])\\s*</\\1>#', '\\2', $text);
         // Convert opening [token] to opening <div data-ui-*> tag.
         $text = preg_replace_callback('#\\[' . $name . '([^]]*)?\\]#is', function ($match) use($name) {
             // Set data-ui-* attributes from role and options.
             $attributes = new Attribute(['data-ui-role' => $name]);
             $options = $this->parseOptions($match[1]);
             foreach ($options as $name => $value) {
                 $attributes->setAttribute('data-ui-' . $name, $value);
             }
             return "<div{$attributes}>";
         }, $text);
         // Convert closing [/token] to closing </div> tag.
         $text = str_replace('[/' . $name . ']', '</div>', $text);
     }
     if ($has_widget) {
         $result->setAttachments(['library' => ['jquery_ui_filter/jquery_ui_filter'], 'drupalSettings' => ['jquery_ui_filter' => \Drupal::config('jquery_ui_filter.settings')->get()]]);
     }
     return $result->setProcessedText($text);
 }
 /**
  * {@inheritdoc}
  */
 public function extract($command)
 {
     $className = substr(strrchr(get_class($command), '\\'), 1);
     return preg_replace_callback('/(^|[a-z])([A-Z])/', function ($s) {
         return strtolower(strlen($s[1]) ? "{$s['1']}_{$s['2']}" : "{$s['2']}");
     }, $className);
 }
示例#25
0
 /**
  *  Prepare content method
  *
  * Method is called by the view
  *
  * @param   string  $context  The context of the content being passed to the plugin.
  * @param   object  &$row     The article object.  Note $article->text is also available
  * @param   object  &$params  The article params
  * @param   int     $page     The 'page' number
  *
  * @return  void
  */
 public function onContentPrepare($context, &$row, &$params, $page = 0)
 {
     jimport('joomla.html.parameter');
     jimport('joomla.filesystem.file');
     // Load fabrik language
     $lang = JFactory::getLanguage();
     $lang->load('com_fabrik', JPATH_BASE . '/components/com_fabrik');
     if (!defined('COM_FABRIK_FRONTEND')) {
         JError::raiseError(400, JText::_('COM_FABRIK_SYSTEM_PLUGIN_NOT_ACTIVE'));
     }
     // Get plugin info
     $plugin = JPluginHelper::getPlugin('content', 'fabrik');
     // $$$ hugh had to rename this, it was stomping on com_content and friends $params
     // $$$ which is passed by reference to us!
     $fparams = new JRegistry($plugin->params);
     // Simple performance check to determine whether bot should process further
     $botRegex = $fparams->get('Botregex') != '' ? $fparams->get('Botregex') : 'fabrik';
     if (JString::strpos($row->text, $botRegex) === false) {
         return true;
     }
     require_once COM_FABRIK_FRONTEND . '/helpers/parent.php';
     /* $$$ hugh - hacky fix for nasty issue with IE, which (for gory reasons) doesn't like having our JS content
      * wrapped in P tags.  But the default WYSIWYG editor in J! will automagically wrap P tags around everything.
      * So let's just look for obvious cases of <p>{fabrik ...}</p>, and replace the P's with DIV's.
      * Yes, it's hacky, but it'll save us a buttload of support work.
      */
     $pregex = "/<p>\\s*{" . $botRegex . "\\s*.*?}\\s*<\\/p>/i";
     $row->text = preg_replace_callback($pregex, array($this, 'preplace'), $row->text);
     // $$$ hugh - having to change this to use {[]}
     $regex = "/{" . $botRegex . "\\s*.*?}/i";
     $row->text = preg_replace_callback($regex, array($this, 'replace'), $row->text);
 }
 /**
  * Convert a string to
  * uppercase and remove
  * accents
  *
  * NOTE: Avoid passing in HTML
  *       This method will dumbly
  *       transform HTML tags and
  *       attributes to uppercase
  *       HTML entities eg: "&nbsp;"
  *       are OK
  *
  * @param string $str
  *
  * @return string
  */
 public static function get_upper($str)
 {
     $all_uppercase = mb_strtoupper(self::remove_accents($str), 'UTF-8');
     return preg_replace_callback('/&([a-z\\d]+);/i', function ($matches) {
         return strtolower($matches[0]);
     }, $all_uppercase);
 }
示例#27
0
 public function tokenizeHTML($html, $config, &$context)
 {
     $html = $this->normalize($html, $config, $context);
     // attempt to armor stray angled brackets that cannot possibly
     // form tags and thus are probably being used as emoticons
     if ($config->get('Core', 'AggressivelyFixLt')) {
         $char = '[^a-z!\\/]';
         $comment = "/<!--(.*?)(-->|\\z)/is";
         $html = preg_replace_callback($comment, array('HTMLPurifier_Lexer_DOMLex', 'callbackArmorCommentEntities'), $html);
         $html = preg_replace("/<({$char})/i", '&lt;\\1', $html);
         $html = preg_replace_callback($comment, array('HTMLPurifier_Lexer_DOMLex', 'callbackUndoCommentSubst'), $html);
         // fix comments
     }
     // preprocess html, essential for UTF-8
     $html = $this->wrapHTML($html, $config, $context);
     $doc = new DOMDocument();
     $doc->encoding = 'UTF-8';
     // theoretically, the above has this covered
     set_error_handler(array($this, 'muteErrorHandler'));
     $doc->loadHTML($html);
     restore_error_handler();
     $tokens = array();
     $this->tokenizeDOM($doc->getElementsByTagName('html')->item(0)->getElementsByTagName('body')->item(0)->getElementsByTagName('div')->item(0), $tokens);
     return $tokens;
 }
示例#28
0
 /**
  * Converts all Hex expressions ("\HEX") to their original ASCII characters
  *
  * @see    Net_LDAP2_Util::hex2asc() from Benedikt Hallinger <*****@*****.**>,
  *         heavily based on work from DavidSmith@byu.net
  * @link   http://pear.php.net/package/Net_LDAP2
  * @author Benedikt Hallinger <*****@*****.**>, heavily based on work from DavidSmith@byu.net
  *
  * @param string $string String to convert
  * @return string
  */
 public static function hex32ToAsc($string)
 {
     $string = preg_replace_callback('/\\\\([0-9A-Fa-f]{2})/', function ($matches) {
         return chr(hexdec($matches[1]));
     }, $string);
     return $string;
 }
示例#29
-2
 function parse_usernames($body)
 {
     $body = preg_replace_callback('/(?<=^|\\s)c\\/([a-z0-9_-]+)(?=$|\\s|:|.)/i', function ($matches) {
         $content = Content::find($matches[1]);
         if ($content) {
             return '[' . str_replace('_', '\\_', $content->title) . '](' . $content->getSlug() . ')';
         } else {
             return 'c/' . $matches[1];
         }
     }, $body);
     $body = preg_replace_callback('/(?<=^|\\s)u\\/([a-z0-9_-]+)(?=$|\\s|:|.)/i', function ($matches) {
         $target = User::name($matches[1])->first();
         if ($target) {
             return '[u/' . str_replace('_', '\\_', $target->name) . '](/u/' . $target->name . ')';
         }
         return 'u/' . $matches[1];
     }, $body);
     $body = preg_replace_callback('/(?<=^|\\s)@([a-z0-9_-]+)(?=$|\\s|:|.)/i', function ($matches) {
         $target = User::name($matches[1])->first();
         if ($target) {
             return '[@' . str_replace('_', '\\_', $target->name) . '](/u/' . $target->name . ')';
         }
         return '@' . $matches[1];
     }, $body);
     $body = preg_replace_callback('/(?<=^|\\s)(?<=\\s|^)g\\/([a-z0-9_-żźćńółęąśŻŹĆĄŚĘŁÓŃ]+)(?=$|\\s|:|.)/i', function ($matches) {
         $target = Group::name($matches[1])->first();
         $fakeGroup = class_exists('Folders\\' . studly_case($matches[1]));
         if ($target || $fakeGroup) {
             $urlname = $target ? $target->urlname : $matches[1];
             return '[g/' . str_replace('_', '\\_', $urlname) . '](/g/' . $urlname . ')';
         }
         return 'g/' . $matches[1];
     }, $body);
     return $body;
 }
示例#30
-11
 /**
  * Minifies stylesheet definitions
  *
  * <code>
  * $css_minified = cssmin::minify(file_get_contents("path/to/target/file.css"));
  * </code>
  *
  * @param	string			$css		Stylesheet definitions as string
  * @param	array|string	$options	Array or comma speperated list of options:
  *
  * 										- remove-last-semicolon: Removes the last semicolon in
  * 										the style definition of an element (activated by default).
  *
  * 										- preserve-urls: Preserves every url defined in an url()-
  * 										expression. This option is only required if you have
  * 										defined really uncommon urls with multiple spaces or
  * 										combination of colon, semi-colon, braces with leading or
  * 										following spaces.
  * @return	string			Minified stylesheet definitions
  */
 public static function minify($css, $options = "remove-last-semicolon")
 {
     $options = $options == "" ? array() : (is_array($options) ? $options : explode(",", $options));
     if (in_array("preserve-urls", $options)) {
         // Encode url() to base64
         $css = preg_replace_callback("/url\\s*\\((.*)\\)/siU", "cssmin_encode_url", $css);
     }
     // Remove comments
     $css = preg_replace("/\\/\\*[\\d\\D]*?\\*\\/|\t+/", " ", $css);
     // Replace CR, LF and TAB to spaces
     $css = str_replace(array("\n", "\r", "\t"), " ", $css);
     // Replace multiple to single space
     $css = preg_replace("/\\s\\s+/", " ", $css);
     // Remove unneeded spaces
     $css = preg_replace("/\\s*({|}|\\[|\\]|=|~|\\+|>|\\||;|:|,)\\s*/", "\$1", $css);
     if (in_array("remove-last-semicolon", $options)) {
         // Removes the last semicolon of every style definition
         $css = str_replace(";}", "}", $css);
     }
     $css = trim($css);
     if (in_array("preserve-urls", $options)) {
         // Decode url()
         $css = preg_replace_callback("/url\\s*\\((.*)\\)/siU", "cssmin_decode_url", $css);
     }
     return $css;
 }