示例#1
0
    public function getDisplaySanitizedValue() {
		$this->load();
		if ($this->akTextareaDisplayMode == 'text') {
			return parent::getDisplaySanitizedValue();
		}
		return htmLawed(parent::getValue(), array('safe'=>1, 'deny_attribute'=>'style'));
	}
示例#2
0
文件: html.php 项目: alerque/bibledit
 public static function run($html)
 {
     include_once "htmLawed.php";
     $config = array('tidy' => 1);
     $html = htmLawed($html, $config);
     return $html;
 }
示例#3
0
文件: model3d.php 项目: komcdo/winnow
function processModel3d($data)
{
    global $abort, $errorArray;
    $data->type = 'model3d';
    //Check name
    if (isset($data->name)) {
        $data->name = strip_tags($data->name);
    } else {
        $data->name = '3D Model';
    }
    //Check key
    if (isset($data->key)) {
        $re = "/^[a-z0-9]{10}\$/";
        //Alphanumeric, and 10 characters
        if (!preg_match($re, $data->key)) {
            $abort = true;
            $errorArray[] = "Invalid key for " . $data->name . " widget.";
        }
    }
    //Check title
    if (isset($data->title)) {
        $data->title = strip_tags($data->title);
    } else {
        $data->title = '3D model title';
    }
    //Check description
    if (isset($data->desc)) {
        $data->desc = htmLawed($data->desc, array('safe' => 1, 'elements' => 'a', 'deny_attribute' => '* -href'));
        $data->desc = str_replace(" />", ">", $data->desc);
    } else {
        $data->desc = "";
    }
    //Check if valid Sketchfab url source
    if (!empty($data->url)) {
        $pattern = "/(?:https?:)?(?:\\/\\/)?(?:www\\.)?(?:sketchfab\\.com\\/models\\/)([a-z0-9]+)(?:.+)?/";
        //Get YouTube video ID
        if (preg_match($pattern, $data->url)) {
            $data->url = preg_replace($pattern, "https://sketchfab.com/models/\$1/embed", $data->url);
        } else {
            $abort = true;
            $errorArray[] = "Sketchfab URL required for " . $data->name . " widget.";
        }
    } else {
        $data->url = "";
    }
    $data = checkAlignment($data);
    //From alignOptions.php
    //Check index is a number
    if (!empty($data->index)) {
        if (!filter_var($data->index, FILTER_VALIDATE_INT) || $data->index < 0) {
            unset($data->index);
        }
    } else {
        //Index is optional
    }
    //Remove any invalid keys
    $validKeys = (object) array('type' => '', 'name' => '', 'key' => '', 'title' => '', 'desc' => '', 'url' => '', 'align' => '', 'margin' => '', 'index' => '');
    $data = (object) array_intersect_key(get_object_vars($data), get_object_vars($validKeys));
    return $data;
}
 public function Format($Html)
 {
     $Attributes = C('Garden.Html.BlockedAttributes', 'on*');
     $Config = array('anti_link_spam' => array('`.`', ''), 'comment' => 1, 'cdata' => 3, 'css_expression' => 1, 'deny_attribute' => $Attributes, 'unique_ids' => 1, 'elements' => '*-applet-form-input-textarea-iframe-script-style-embed-object-select-option-button-fieldset-optgroup-legend', 'keep_bad' => 0, 'schemes' => 'classid:clsid; href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; style: nil; *:file, http, https', 'valid_xhtml' => 0, 'direct_list_nest' => 1, 'balance' => 1);
     // Turn embedded videos into simple links (legacy workaround)
     $Html = Gdn_Format::UnembedVideos($Html);
     // We check the flag within Gdn_Format to see
     // if htmLawed should place rel="nofollow" links
     // within output or not.
     // A plugin can set this flag (for example).
     // The default is to show rel="nofollow" on all links.
     if (Gdn_Format::$DisplayNoFollow) {
         // display rel="nofollow" on all links.
         $Config['anti_link_spam'] = array('`.`', '');
     } else {
         // never display rel="nofollow"
         $Config['anti_link_spam'] = array('', '');
     }
     if ($this->SafeStyles) {
         // Deny all class and style attributes.
         // A lot of damage can be done by hackers with these attributes.
         $Config['deny_attribute'] .= ',style';
         //      } else {
         //         $Config['hook_tag'] = 'HTMLawedHookTag';
     }
     // Block some IDs so you can't break Javascript
     $GLOBALS['hl_Ids'] = array('Bookmarks' => 1, 'CommentForm' => 1, 'Content' => 1, 'Definitions' => 1, 'DiscussionForm' => 1, 'Foot' => 1, 'Form_Comment' => 1, 'Form_User_Password' => 1, 'Form_User_SignIn' => 1, 'Head' => 1, 'HighlightColor' => 1, 'InformMessageStack' => 1, 'Menu' => 1, 'PagerMore' => 1, 'Panel' => 1, 'Status' => 1);
     $Spec = 'object=-classid-type, -codebase; embed=type(oneof=application/x-shockwave-flash); a=class(noneof=Hijack|Dismiss|MorePager/nomatch=%pop[in|up|down]|flyout|ajax%i)';
     $Result = htmLawed($Html, $Config, $Spec);
     return $Result;
 }
示例#5
0
文件: video.php 项目: komcdo/winnow
function processVideo($data)
{
    global $abort, $errorArray;
    $data->type = 'video';
    //Check name
    if (isset($data->name)) {
        $data->name = strip_tags($data->name);
    } else {
        $data->name = 'Video';
    }
    //Check key
    if (isset($data->key)) {
        $re = "/^[a-z0-9]{10}\$/";
        //Alphanumeric, and 10 characters
        if (!preg_match($re, $data->key)) {
            $abort = true;
            $errorArray[] = "Invalid key for " . $data->name . " widget.";
        }
    }
    //Check title
    if (isset($data->title)) {
        $data->title = strip_tags($data->title);
    } else {
        $data->title = 'Sample title';
    }
    //Check description
    if (isset($data->desc)) {
        $data->desc = htmLawed($data->desc, array('safe' => 1, 'elements' => 'a', 'deny_attribute' => '* -href'));
        $data->desc = str_replace(" />", ">", $data->desc);
    } else {
        $data->desc = "";
    }
    //Check if valid YouTube url source
    if (!empty($data->url)) {
        $pattern = "/(?:https?:)?(?:\\/\\/)?(?:www\\.)?(?:youtube\\.com|youtu\\.be)\\/(?:embed\\/)?(?:watch\\?v=)?([a-zA-Z0-9_-]+)(?:\\?.+)?(?:&.+)?\$/";
        //Get YouTube video ID
        if (preg_match($pattern, $data->url)) {
            $data->url = preg_replace($pattern, "//www.youtube.com/embed/\$1?rel=0&amp;showinfo=0", $data->url);
        } else {
            $abort = true;
            $errorArray[] = "YouTube video URL required for " . $data->name . " widget.";
        }
    } else {
        $data->url = "";
    }
    $data = checkAlignment($data);
    //From alignOptions.php
    //Check index is a number
    if (!empty($data->index)) {
        if (!filter_var($data->index, FILTER_VALIDATE_INT) || $data->index < 0) {
            unset($data->index);
        }
    } else {
        //Index is optional
    }
    //Remove any invalid keys
    $validKeys = (object) array('type' => '', 'name' => '', 'key' => '', 'title' => '', 'desc' => '', 'url' => '', 'align' => '', 'margin' => '', 'index' => '');
    $data = (object) array_intersect_key(get_object_vars($data), get_object_vars($validKeys));
    return $data;
}
示例#6
0
 public function Format($Html)
 {
     $Config = array('anti_link_spam' => array('`.`', ''), 'comment' => 1, 'cdata' => 3, 'css_expression' => 1, 'deny_attribute' => 'on*', 'elements' => '*-applet-form-input-textarea-iframe-script-style', 'keep_bad' => 0, 'schemes' => 'classid:clsid; href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; style: nil; *:file, http, https', 'valid_xhtml' => 0, 'direct_list_nest' => 1, 'balance' => 1);
     // We check the flag within Gdn_Format to see
     // if htmLawed should place rel="nofollow" links
     // within output or not.
     // A plugin can set this flag (for example).
     // The default is to show rel="nofollow" on all links.
     if (Gdn_Format::$DisplayNoFollow) {
         // display rel="nofollow" on all links.
         $Config['anti_link_spam'] = array('`.`', '');
     } else {
         // never display rel="nofollow"
         $Config['anti_link_spam'] = array('', '');
     }
     if ($this->SafeStyles) {
         // Deny all class and style attributes.
         // A lot of damage can be done by hackers with these attributes.
         $Config['deny_attribute'] .= ',style';
         //      } else {
         //         $Config['hook_tag'] = 'HTMLawedHookTag';
     }
     $Spec = 'object=-classid-type, -codebase; embed=type(oneof=application/x-shockwave-flash)';
     $Result = htmLawed($Html, $Config, $Spec);
     return $Result;
 }
示例#7
0
文件: image.php 项目: komcdo/winnow
function processImageWidget($data)
{
    global $abort, $errorArray;
    $data->type = 'imagewidget';
    //Check name
    if (isset($data->name)) {
        $data->name = strip_tags($data->name);
    } else {
        $data->name = 'Image';
    }
    //Check key
    if (isset($data->key)) {
        $re = "/^[a-z0-9]{10}\$/";
        //Alphanumeric, and 10 characters
        if (!preg_match($re, $data->key)) {
            $abort = true;
            $errorArray[] = "Invalid key for " . $data->name . " widget.";
        }
    }
    //Check title
    if (isset($data->title)) {
        $data->title = strip_tags($data->title);
    } else {
        $data->title = 'Sample title';
    }
    //Check description
    if (isset($data->desc)) {
        $data->desc = htmLawed($data->desc, array('safe' => 1, 'elements' => 'a', 'deny_attribute' => '* -href'));
        $data->desc = str_replace(" />", ">", $data->desc);
    } else {
        $data->desc = "";
    }
    //Check image source
    if (!empty($data->imgSrc)) {
        if (!file_exists(ROOT_PATH . ltrim($data->imgSrc, '/')) && !file_exists($data->imgSrc)) {
            $abort = true;
            $errorArray[] = $data->name . " image source not found.";
        }
    } else {
        $abort = true;
        $errorArray[] = "Image source required for " . $data->name . " widget.";
    }
    $data = checkAlignment($data);
    //From alignOptions.php
    //Check index is a number
    if (!empty($data->index)) {
        if (!filter_var($data->index, FILTER_VALIDATE_INT) || $data->index < 0) {
            unset($data->index);
        }
    } else {
        //Index is optional
    }
    //Remove any invalid keys
    $validKeys = (object) array('type' => '', 'name' => '', 'key' => '', 'title' => '', 'desc' => '', 'imgSrc' => '', 'align' => '', 'margin' => '', 'index' => '');
    $data = (object) array_intersect_key(get_object_vars($data), get_object_vars($validKeys));
    return $data;
}
 public static function xssClean($value)
 {
     if (!is_array($value)) {
         return htmLawed($value, array('safe' => 1, 'balanced' => 0));
     }
     foreach ($value as $k => $v) {
         $value[$k] = $this->xss_clean($v);
     }
     return $value;
 }
示例#9
0
 public static function xss_clean($value, array $options = array())
 {
     if (!is_array($value)) {
         if (!function_exists('htmLawed')) {
             require_once dirname(dirname(__FILE__)) . '/vendor/htmlawed.php';
         }
         return htmLawed($value, array_merge(array('safe' => 1, 'balanced' => 0), $options));
     }
     foreach ($value as $k => $v) {
         $value[$k] = static::xss_clean($v);
     }
     return $value;
 }
示例#10
0
文件: Graby.php 项目: harikt/graby
 /**
  * Fetch content from the given url and return a readable content.
  *
  * @param string $url
  *
  * @return array With keys html, title, url & summary
  */
 public function fetchContent($url)
 {
     $infos = $this->doFetchContent($url);
     $html = $infos['html'];
     // filter xss?
     if ($this->config['xss_filter']) {
         $this->logger->log('debug', 'Filtering HTML to remove XSS');
         $html = htmLawed($html, array('safe' => 1, 'deny_attribute' => 'style', 'comment' => 1, 'cdata' => 1));
     }
     // generate summary
     $infos['summary'] = $this->getExcerpt($html);
     return $infos;
 }
示例#11
0
 public static function repairHtml($html, $config = array())
 {
     if (class_exists('tidy')) {
         $config = array_merge(array('indent' => true, 'output-xhtml' => true, 'clean' => false, 'wrap' => '86', 'doctype' => 'omit', 'drop-proprietary-attributes' => true, 'drop-font-tags' => false, 'word-2000' => true, 'show-body-only' => true, 'bare' => true, 'enclose-block-text' => true, 'enclose-text' => true, 'join-styles' => false, 'join-classes' => false, 'logical-emphasis' => true, 'lower-literals' => true, 'literal-attributes' => false, 'indent-spaces' => 2, 'quote-nbsp' => true, 'output-bom' => false, 'char-encoding' => 'utf8', 'newline' => 'LF', 'uppercase-tags' => false), $config);
         $tidy = new tidy();
         $tidy->parseString($html, $config, 'utf8');
         $tidy->cleanRepair();
         $ret = $tidy->value;
     } else {
         require_once VENDOR_PATH . '/koala-framework/library-htmlawed/htmLawed.php';
         $ret = htmLawed($html);
     }
     return $ret;
 }
示例#12
0
 /**
  * Filters a string of html with the htmLawed library.
  *
  * @param string $html The text to filter.
  * @param array|null $config Config settings for the array.
  * @param string|array|null $spec A specification to further limit the allowed attribute values in the html.
  * @return string Returns the filtered html.
  * @see http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/htmLawed_README.htm
  */
 public static function filter($html, array $config = null, $spec = null)
 {
     require_once __DIR__ . '/htmLawed/htmLawed.php';
     if ($config === null) {
         $config = self::$defaultConfig;
     }
     if (isset($config['spec']) && !$spec) {
         $spec = $config['spec'];
     }
     if ($spec === null) {
         $spec = static::$defaultSpec;
     }
     return htmLawed($html, $config, $spec);
 }
 public function Format($Html)
 {
     $Config = array('anti_link_spam' => array('`.`', ''), 'comment' => 1, 'cdata' => 3, 'css_expression' => 1, 'deny_attribute' => 'on*', 'elements' => '*-applet-form-input-textarea-iframe-script-style', 'keep_bad' => 0, 'schemes' => 'classid:clsid; href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; style: nil; *:file, http, https', 'valid_xml' => 2);
     if ($this->SafeStyles) {
         // Deny all class and style attributes.
         // A lot of damage can be done by hackers with these attributes.
         $Config['deny_attribute'] .= ',style';
     } else {
         $Config['hook_tag'] = 'HTMLawedHookTag';
     }
     $Spec = 'object=-classid-type, -codebase; embed=type(oneof=application/x-shockwave-flash)';
     $Result = htmLawed($Html, $Config, $Spec);
     return $Result;
 }
示例#14
0
 public function Format($String)
 {
     $String = str_replace(array('&quot;', '&#39;', '&#58;', 'Â'), array('"', "'", ':', ''), $String);
     $String = str_replace('<#EMO_DIR#>', 'default', $String);
     $String = str_replace('<{POST_SNAPBACK}>', '<span class="SnapBack">»</span>', $String);
     // There is an issue with using uppercase code blocks, so they're forced to lowercase here
     $String = str_replace(array('[CODE]', '[/CODE]'), array('[code]', '[/code]'), $String);
     /**
      * IPB inserts line break markup tags at line breaks.  They need to be removed in code blocks.
      * The original newline/line break should be left intact, so whitespace will be preserved in the pre tag.
      */
     $String = preg_replace_callback('/\\[code\\].*?\\[\\/code\\]/is', function ($CodeBlocks) {
         return str_replace(array('<br />'), array(''), $CodeBlocks[0]);
     }, $String);
     /**
      * IPB formats some quotes as HTML.  They're converted here for the sake of uniformity in presentation.
      * Attribute order seems to be standard.  Spacing between the opening of the tag and the first attribute is variable.
      */
     $String = preg_replace_callback('#<blockquote\\s+class="ipsBlockquote" data-author="([^"]+)" data-cid="(\\d+)" data-time="(\\d+)">(.*?)</blockquote>#is', function ($BlockQuotes) {
         $Author = $BlockQuotes[1];
         $Cid = $BlockQuotes[2];
         $Time = $BlockQuotes[3];
         $QuoteContent = $BlockQuotes[4];
         // $Time will over as a timestamp. Convert it to a date string.
         $Date = date('F j Y, g:i A', $Time);
         return "[quote name=\"{$Author}\" url=\"{$Cid}\" date=\"{$Date}\"]{$QuoteContent}[/quote]";
     }, $String);
     // If there is a really long string, it could cause a stack overflow in the bbcode parser.
     // Not much we can do except try and chop the data down a touch.
     // 1. Remove html comments.
     $String = preg_replace('/<!--(.*)-->/Uis', '', $String);
     // 2. Split the string up into chunks.
     $Strings = (array) $String;
     $Result = '';
     foreach ($Strings as $String) {
         $Result .= $this->NBBC()->Parse($String);
     }
     // Linkify URLs in content
     $Result = Gdn_Format::links($Result);
     // Parsing mentions
     $Result = Gdn_Format::mentions($Result);
     // Handling emoji
     $Result = Emoji::instance()->translateToHtml($Result);
     // Make sure to clean filter the html in the end.
     $Config = array('anti_link_spam' => array('`.`', ''), 'comment' => 1, 'cdata' => 3, 'css_expression' => 1, 'deny_attribute' => 'on*', 'elements' => '*-applet-form-input-textarea-iframe-script-style', 'keep_bad' => 0, 'schemes' => 'classid:clsid; href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; style: nil; *:file, http, https', 'valid_xml' => 2);
     $Spec = 'object=-classid-type, -codebase; embed=type(oneof=application/x-shockwave-flash)';
     $Result = htmLawed($Result, $Config, $Spec);
     return $Result;
 }
示例#15
0
 /**
  * Clean display value deleting html tags
  *
  * @param $value string: string value
  * @param $striptags bool: strip all html tags
  * @param $keep_bad int:
  *          1 : neutralize tag anb content,
  *          2 : remove tag and neutralize content
  * @return clean value
  **/
 static function clean($value, $striptags = true, $keep_bad = 2)
 {
     include_once GLPI_HTMLAWED;
     $value = Html::entity_decode_deep($value);
     // Clean MS office tags
     $value = str_replace(array("<![if !supportLists]>", "<![endif]>"), '', $value);
     if ($striptags) {
         $specialfilter = array('@<div[^>]*?tooltip_picture[^>]*?>.*?</div[^>]*?>@si');
         // Strip ToolTips
         $value = preg_replace($specialfilter, '', $value);
         $specialfilter = array('@<div[^>]*?tooltip_text[^>]*?>.*?</div[^>]*?>@si');
         // Strip ToolTips
         $value = preg_replace($specialfilter, '', $value);
         $specialfilter = array('@<div[^>]*?tooltip_picture_border[^>]*?>.*?</div[^>]*?>@si');
         // Strip ToolTips
         $value = preg_replace($specialfilter, '', $value);
         $specialfilter = array('@<div[^>]*?invisible[^>]*?>.*?</div[^>]*?>@si');
         // Strip ToolTips
         $value = preg_replace($specialfilter, '', $value);
         $value = preg_replace("/<(p|br|div)( [^>]*)?" . ">/i", "\n", $value);
         $value = preg_replace("/(&nbsp;| )+/", " ", $value);
         $search = array('@<script[^>]*?>.*?</script[^>]*?>@si', '@<style[^>]*?>.*?</style[^>]*?>@si', '@<!DOCTYPE[^>]*?>@si');
         $value = preg_replace($search, '', $value);
     }
     $value = htmLawed($value, array('elements' => $striptags ? 'none' : '', 'keep_bad' => $keep_bad, 'comment' => 1, 'cdata' => 1));
     $value = str_replace(array('&lt;', '&gt;'), array('&amp;lt;', '&amp;gt;'), $value);
     /*
           $specialfilter = array('@<span[^>]*?x-hidden[^>]*?>.*?</span[^>]*?>@si'); // Strip ToolTips
           $value         = preg_replace($specialfilter, ' ', $value);
     
           $search        = array('@<script[^>]*?>.*?</script[^>]*?>@si', // Strip out javascript
                                  '@<style[^>]*?>.*?</style[^>]*?>@si',   // Strip style tags properly
                                  '@<[\/\!]*?[^<>]*?>@si',                // Strip out HTML tags
                                  '@<![\s\S]*?--[ \t\n\r]*>@');           // Strip multi-line comments including CDATA
     
           $value = preg_replace($search, ' ', $value);
     
           // nettoyer l'apostrophe curly qui pose probleme a certains rss-readers, lecteurs de mail...
           $value = str_replace("&#8217;", "'", $value);
     */
     // Problem with this regex : may crash
     //   $value = preg_replace("/ +/u", " ", $value);
     // Revert back htmlawed &amp; -> &
     //$value = str_replace("&amp;", "&", $value);
     $value = str_replace(array("\r\n", "\r"), "\n", $value);
     $value = preg_replace("/(\n[ ]*){2,}/", "\n\n", $value, -1);
     return trim($value);
 }
示例#16
0
 /**
  * Sanitize HTML
  *
  * @param string $html the html to sanitize
  * @param int $trusted -1, 0, or 1
  * @return string sanitized html
  */
 static function sanitizeHtml($html, $trusted = -1)
 {
     if ($trusted > 0) {
         // Allow all (*) except -script and -iframe
         $config = array('elements' => '*-script-iframe');
     } elseif ($trusted < 0) {
         // Paranoid mode, i.e. only allow a small subset of elements to pass
         // Transform strike and u to span for better XHTML 1-strict compliance
         $config = array('safe' => 1, 'elements' => 'a,em,strike,strong,u,p,br,img,li,ol,ul', 'make_tag_strict' => 1);
     } else {
         // Safe
         $config = array('safe' => 1, 'deny_attribute' => 'style,class', 'comment' => 1);
     }
     require_once dirname(__FILE__) . '/symbionts/htmLawed/htmLawed.php';
     return htmLawed($html, $config);
 }
示例#17
0
function SaveAlertContent($id, $content)
{
    global $connection;
    //filter HTML content with htmLawed
    $content = urldecode($content);
    include "../core/libs/htmLawed.php";
    $content = htmLawed($content, array('safe' => 1));
    //temporary htmLawed settings, move to configuration.php
    $content = $connection->real_escape_string($content);
    $request = "UPDATE alerts_content SET content='{$content}' WHERE id='{$id}'";
    $connection->query($request);
    if ($connection->error) {
        die("failed");
    } else {
        echo "success";
    }
}
function importActivityStream($user, $doc)
{
    $feed = $doc->documentElement;
    $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
    for ($i = $entries->length - 1; $i >= 0; $i--) {
        $entry = $entries->item($i);
        $activity = new Activity($entry, $feed);
        $object = $activity->objects[0];
        if (!have_option('q', 'quiet')) {
            print $activity->content . "\n";
        }
        $html = getTweetHtml($object->link);
        $config = array('safe' => 1, 'deny_attribute' => 'class,rel,id,style,on*');
        $html = htmLawed($html, $config);
        $content = html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8');
        $notice = Notice::saveNew($user->id, $content, 'importtwitter', array('uri' => $object->id, 'url' => $object->link, 'rendered' => $html, 'created' => common_sql_date($activity->time), 'replies' => array(), 'groups' => array()));
    }
}
/**
 * htmLawed filtering of tags, called on a plugin hook
 *
 * @param mixed $var Variable to filter
 * @return mixed
 */
function htmlawed_filter_tags($hook, $entity_type, $returnvalue, $params)
{
    $return = $returnvalue;
    $var = $returnvalue;
    if (include_once dirname(__FILE__) . "/vendors/htmLawed/htmLawed.php") {
        global $CONFIG;
        $htmlawed_config = $CONFIG->htmlawed_config;
        if (!is_array($var)) {
            $return = "";
            $return = htmLawed($var, $htmlawed_config);
        } else {
            $return = array();
            foreach ($var as $key => $el) {
                $return[$key] = htmLawed($el, $htmlawed_config);
            }
        }
    }
    return $return;
}
示例#20
0
文件: DText.php 项目: JCQS04/myimouto
 public static function parse($str)
 {
     $state = ['newline'];
     $result = '';
     # Normalize newlines.
     $str = trim($str);
     $str = preg_replace(['/(\\r\\n?)/', '/\\n{3,}/', '/ *\\n */'], ["\n", "\n\n", "\n"], $str);
     $str = htmlentities($str);
     # Keep newline, use carriage return for split.
     $str = str_replace("\n", "\n\r", $str);
     $data = explode("\r", $str);
     # Parse header and list first, line by line.
     foreach ($data as $d) {
         $result .= self::parseline($d, $state);
     }
     # Parse inline tags as a whole.
     $result = self::parseinline($result);
     # htmLawed ensures valid html output.
     require_once Rails::root() . '/vendor/htmLawed/htmLawed.php';
     return htmLawed($result);
 }
示例#21
0
 /**
  * Clean display value deleting html tags
  *
  * @param $value string: string value
  * @param $striptags bool: strip all html tags
  * @param $keep_bad int:
  *          1 : neutralize tag anb content,
  *          2 : remove tag and neutralize content
  * @return clean value
  **/
 static function clean($value, $striptags = true, $keep_bad = 2)
 {
     $value = Html::entity_decode_deep($value);
     // Clean MS office tags
     $value = str_replace(array("<![if !supportLists]>", "<![endif]>"), '', $value);
     if ($striptags) {
         // Strip ToolTips
         $specialfilter = array('@<div[^>]*?tooltip_picture[^>]*?>.*?</div[^>]*?>@si', '@<div[^>]*?tooltip_text[^>]*?>.*?</div[^>]*?>@si', '@<div[^>]*?tooltip_picture_border[^>]*?>.*?</div[^>]*?>@si', '@<div[^>]*?invisible[^>]*?>.*?</div[^>]*?>@si');
         $value = preg_replace($specialfilter, '', $value);
         $value = preg_replace("/<(p|br|div)( [^>]*)?" . ">/i", "\n", $value);
         $value = preg_replace("/(&nbsp;| | )+/", " ", $value);
     }
     $search = array('@<script[^>]*?>.*?</script[^>]*?>@si', '@<style[^>]*?>.*?</style[^>]*?>@si', '@<title[^>]*?>.*?</title[^>]*?>@si', '@<!DOCTYPE[^>]*?>@si');
     $value = preg_replace($search, '', $value);
     // Neutralize not well formatted html tags
     $value = preg_replace("/(<)([^>]*<)/", "&lt;\$2", $value);
     include_once GLPI_HTMLAWED;
     $value = htmLawed($value, array('elements' => $striptags ? 'none' : '', 'keep_bad' => $keep_bad, 'comment' => 1, 'cdata' => 1));
     $value = str_replace(array("\r\n", "\r"), "\n", $value);
     $value = preg_replace("/(\n[ ]*){2,}/", "\n\n", $value, -1);
     return trim($value);
 }
示例#22
0
文件: textBox.php 项目: komcdo/winnow
function processTextBox($data)
{
    $data->type = 'textBox';
    if (isset($data->name)) {
        $data->name = strip_tags($data->name);
    } else {
        $data->name = 'Text Box';
    }
    //Check key
    if (isset($data->key)) {
        $re = "/^[a-z0-9]{10}\$/";
        //Alphanumeric, and 10 characters
        if (!preg_match($re, $data->key)) {
            $abort = true;
            $errorArray[] = "Invalid key for " . $data->name . " widget.";
        }
    }
    if (isset($data->text)) {
        //$data->text = escapeMathML($data->text);
        $data->text = htmLawed($data->text, array('safe' => 1, 'elements' => '*', 'deny_attribute' => ''), 'span=glossary-term, term-id, desc-index, reference, ref-ids, widget-reference, widget-id, widget-desc');
        //$data->text = restoreMathML($data->text);
        $data->text = str_replace(" />", ">", $data->text);
    } else {
        $data->text = "";
    }
    //Check index is a number
    if (!empty($data->index)) {
        if (!filter_var($data->index, FILTER_VALIDATE_INT) || $data->index < 0) {
            unset($data->index);
        }
    } else {
        //Index is optional
    }
    //Remove any invalid keys
    $validKeys = (object) array('type' => '', 'name' => '', 'text' => '', 'index' => '', 'key' => '');
    $data = (object) array_intersect_key(get_object_vars($data), get_object_vars($validKeys));
    return $data;
}
示例#23
0
 function on_submit()
 {
     $footerContent = Url::get('content');
     if (get_magic_quotes_gpc()) {
         $footerContent = stripslashes($footerContent);
     }
     require_once ROOT_PATH . 'includes/htmLawed.php';
     $config = array('safe' => 1, 'elements' => '*', 'deny_attribute' => 'class, id');
     $spec = 'a = title, href;';
     // The 'a' element can have only these attributes
     $footerContent = htmLawed($footerContent, $config, $spec);
     $footerContent = AZLib::clean_value($footerContent);
     $this->checkFormInput('Nội dung', 'content', $footerContent, 'str', true);
     if (!$this->errNum) {
         if (isset(CGlobal::$configs['footer_content'])) {
             DB::update('configs', array("conf_val" => $footerContent), "conf_key='footer_content'");
         } else {
             DB::insert('configs', array("conf_key" => 'footer_content', "conf_val" => $footerContent));
         }
         AZLib::get_config(0, 1);
         AZLib::refreshParent();
     }
 }
示例#24
0
 /**
  * Compliance with XHTML standards, rid cruft generated by word processors
  *
  * @param string $html
  *
  * @return string $html
  */
 protected function tidy($html)
 {
     // Reduce the vulnerability for scripting attacks
     // Make XHTML 1.1 strict using htmlLawed
     $config = array('deny_attribute' => 'style', 'comment' => 1, 'safe' => 1, 'valid_xhtml' => 1, 'no_deprecated_attr' => 2, 'hook' => '\\Pressbooks\\Sanitize\\html5_to_xhtml11');
     return htmLawed($html, $config);
 }
示例#25
0
 private static function _htmLawed($str, $permissions)
 {
     global $_CONF, $_USER;
     require_once $_CONF['path_system'] . 'classes/htmlawed/htmLawed.php';
     // Sets config options for htmLawed.  See http://www.bioinformatics.org/
     // phplabware/internal_utilities/htmLawed/htmLawed_README.htm
     $config = array('balance' => 1, 'comment' => 3, 'css_expression' => 1, 'keep_bad' => 0, 'tidy' => 0, 'unique_ids' => 1, 'valid_xhtml' => 1);
     if (isset($_CONF['allowed_protocols']) && is_array($_CONF['allowed_protocols']) && count($_CONF['allowed_protocols']) > 0) {
         $schemes = $_CONF['allowed_protocols'];
     } else {
         $schemes = array('http:', 'https:', 'ftp:');
     }
     $schemes = str_replace(':', '', implode(', ', $schemes));
     $config['schemes'] = 'href: ' . $schemes . '; *: ' . $schemes;
     if (empty($permissions) || !SEC_hasRights($permissions) || empty($_CONF['admin_html'])) {
         $html = $_CONF['user_html'];
     } else {
         if ($_CONF['advanced_editor'] && $_USER['advanced_editor']) {
             $html = array_merge_recursive($_CONF['user_html'], $_CONF['admin_html'], $_CONF['advanced_html']);
         } else {
             $html = array_merge_recursive($_CONF['user_html'], $_CONF['admin_html']);
         }
     }
     foreach ($html as $tag => $attr) {
         if (is_array($attr) && count($attr) > 0) {
             $spec[] = $tag . '=' . implode(', ', array_keys($attr));
         } else {
             $spec[] = $tag . '=-*';
         }
         $elements[] = $tag;
     }
     $config['elements'] = implode(', ', $elements);
     $spec = implode('; ', $spec);
     $str = htmLawed($str, $config, $spec);
     return $str;
 }
示例#26
0
 if ($system->SETTINGS['usersauth'] == 'y') {
     // hash and check the password
     include $include_path . 'PasswordHash.php';
     $phpass = new PasswordHash(8, false);
     if (!$phpass->CheckPassword($_POST['password'], $user->user_data['password'])) {
         $ERR = 'ERR_026';
     }
 }
 if ($ERR != 'ERR_') {
     $_SESSION['action'] = 2;
 } else {
     // clean up sell description
     $conf = array();
     $conf['safe'] = 1;
     $conf['deny_attribute'] = 'style';
     $_SESSION['SELL_description'] = htmLawed($_SESSION['SELL_description'], $conf);
     $payment_text = implode(', ', $payment);
     // set time back to GMT
     $a_starts = empty($start_now) || $_SESSION['SELL_action'] == 'edit' ? $a_starts - $system->tdiff : time();
     $a_ends = $a_starts + $duration * 24 * 60 * 60;
     // get fee
     $fee_data = get_fee($minimum_bid, false);
     $fee = $fee_data[0];
     $fee_data = $fee_data[1];
     if ($_SESSION['SELL_action'] == 'edit') {
         updateauction(1);
     }
     if ($_SESSION['SELL_action'] == 'relist') {
         remove_bids($_SESSION['SELL_auction_id']);
         // incase they've not already been removed
         updateauction(2);
示例#27
0
文件: service.php 项目: Galinijay/PAS
	***/
if (isset($_POST) && count($_POST)) {
    /*
    	Préparation des données : on crée un array contenant toutes les données, ce dernier sera ensuite parcouru pour créer la requête SQL qui sera préparée
    */
    // Ce qui est propre aux edit et delete
    if (($action == 'edit' || $action == 'delete') && isset($serviceInfo)) {
        $sqlData['id'] = $serviceInfo['id'];
        // Id du service
    }
    // Traitement du POST
    if ($action == 'edit' || $action == 'add') {
        foreach ($_POST as $key => $value) {
            if ($key == 'nom') {
                if ($value != '' && ($action == 'add' || $value != $serviceInfo[$key])) {
                    $sqlData[$key] = htmLawed($value);
                }
            }
            if ($key == 'chef' && is_numeric($value) && count(checkUser($value, array())) == 0 && ($action == 'add' || $value != $serviceInfo[$key])) {
                $sqlData[$key] = $value;
            }
            if ($key == 'hopital' && is_numeric($value) && count(checkHopital($value, array())) == 0 && ($action == 'add' || $value != $serviceInfo[$key])) {
                $sqlData[$key] = $value;
            }
            if ($key == 'specialite' && is_numeric($value) && count(checkSpecialite($value, array())) == 0 && ($action == 'add' || $value != $serviceInfo[$key])) {
                $sqlData[$key] = $value;
            }
            if ($key == 'certificat') {
                $sqlAffectationData = array();
                $currentCertificat = array();
                if (isset($serviceInfo)) {
示例#28
0
 public static function xss_clean($value)
 {
     if (!is_array($value)) {
         if (!function_exists('htmLawed')) {
             import('htmlawed/htmlawed', 'vendor');
         }
         return htmLawed($value, array('safe' => 1, 'balanced' => 0));
     }
     foreach ($value as $k => $v) {
         $value[$k] = static::xss_clean($v);
     }
     return $value;
 }
示例#29
0
/**
 * processCCPCformData - Vérifie et traite les données retournées par le formulaire 
 *
 * @category : eval_ccpc_functions
 * @param array $formData Array contenant les données à traiter
 * @param array $evaluationData Array contenant les informations relatives à l'évaluation
 * @return array Array contenant les informations de formData après qu'elles aient été traités et les erreurs rencontrés lors de l'execution de la fonction
 * 
 * @Author Ali Bellamine
 *
 * Contenu de l'array retourné :<br>
 *	['erreur'][] => (array) Array contenant les erreurs<br>
 *	[nom du champs dans la base de donnée] => valeur fournie par l'utilisateur
 */
function processCCPCformData($formData, $evaluationData)
{
    global $db;
    $formResult = array();
    $erreur = array();
    // On parcours le fichier XML
    if (is_file(PLUGIN_PATH . 'formulaire.xml')) {
        if ($form = simplexml_load_file(PLUGIN_PATH . 'formulaire.xml')) {
            foreach ($form->categorie as $categorie) {
                foreach ($categorie->input as $input) {
                    if ($input['type'] == 'select') {
                        $allowedValue[] = array();
                        foreach ($input->option as $option) {
                            $allowedValue[] = $option['value'];
                        }
                        if (isset($formData[(string) $input['name']]) && in_array($formData[(string) $input['name']], $allowedValue)) {
                            $formResult[(string) $input['nomBDD']] = $formData[(string) $input['name']];
                        } else {
                            if (isset($input['required']) && $input['required'] == 1) {
                                $erreur['LANG_ERROR_CCPC_INCOMPLETEFORM'] = true;
                            } else {
                                $formResult[(string) $input['nomBDD']] = '';
                            }
                        }
                    } else {
                        if ($input['type'] == 'checkbox') {
                            foreach ($input->checkbox as $checkbox) {
                                if (isset($formData[(string) $input['name']]) && in_array((string) $checkbox["value"], $formData[(string) $input['name']])) {
                                    $formResult[(string) $checkbox['nomBDD']] = 1;
                                } else {
                                    $formResult[(string) $checkbox['nomBDD']] = 0;
                                }
                            }
                        } else {
                            if ($input['type'] == 'radio') {
                                $allowedValue[] = array();
                                foreach ($input->radio as $radio) {
                                    $allowedValue[] = $radio['value'];
                                }
                                if (isset($formData[(string) $input['name']]) && in_array($formData[(string) $input['name']], $allowedValue)) {
                                    $formResult[(string) $input['nomBDD']] = $formData[(string) $input['name']];
                                } else {
                                    if (isset($input['required']) && $input['required'] == 1) {
                                        $erreur['LANG_ERROR_CCPC_INCOMPLETEFORM'] = true;
                                    } else {
                                        $formResult[(string) $input['nomBDD']] = '';
                                    }
                                }
                            } else {
                                if ($input['type'] == 'text') {
                                    foreach ($input->text as $text) {
                                        if (isset($text['required']) && $text['required'] == 1 && (!isset($formData[(string) $text['name']]) || $formData[(string) $text['name']] == '')) {
                                            $erreur['LANG_ERROR_CCPC_INCOMPLETEFORM'] = true;
                                        } else {
                                            if (isset($formData[(string) $text['name']])) {
                                                $formResult[(string) $text['nomBDD']] = htmLawed($formData[(string) $text['name']]);
                                            } else {
                                                $formResult[(string) $text['nomBDD']] = '';
                                            }
                                        }
                                    }
                                } else {
                                    if ($input['type'] == 'textarea') {
                                        if (isset($input['required']) && $input['required'] == 1 && (!isset($formData[(string) $input['name']]) || $formData[(string) $input['name']] == '')) {
                                            $erreur['LANG_ERROR_CCPC_INCOMPLETEFORM'] = true;
                                        } else {
                                            if (isset($formData[(string) $input['name']])) {
                                                $formResult[(string) $input['nomBDD']] = htmLawed($formData[(string) $input['name']]);
                                            } else {
                                                $formResult[(string) $input['nomBDD']] = '';
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    /**
    		Récupération des données non incluses dans le formulaire (promotion, nb d'externe, service, etc...)
    	**/
    if (count($erreur) == 0) {
        $nonEvaluationData = eval_ccpc_getNoFormData($evaluationData, $erreur);
        /*
        	On récupère la liste des services déjà évalués
        */
        if (getEvaluationRegisterData() != '') {
            $evaluateService = unserialize(getEvaluationRegisterData());
        } else {
            $evaluateService = array();
        }
        /*
        	On retire les services déjà évalués de la liste des services à évaluer
        */
        foreach ($evaluateService as $service) {
            if (isset($nonEvaluationData['data'][$service])) {
                unset($nonEvaluationData['data'][$service]);
            }
        }
        // On récupère les données qui ne sont pas d'évaluation
        if (isset($nonEvaluationData['data']) && count($nonEvaluationData['data']) > 0) {
            if (isset($formData['service']) && isset($nonEvaluationData['data'][$formData['service']])) {
                $formResult = array_merge($formResult, $nonEvaluationData['data'][$formData['service']]);
                // On récupère les données d'évaluation
            } else {
                $erreur['LANG_ERROR_CCPC_INCOMPLETEFORM'] = true;
            }
        }
        // On récupère les erreurs
        if (isset($nonEvaluationData['erreur']) && count($nonEvaluationData['erreur']) > 0) {
            if (isset($formData['service']) && isset($nonEvaluationData['erreur'][$formData['service']])) {
                $erreur = array_merge($erreur, $nonEvaluationData['erreur'][$formData['service']]);
                // On récupère les données d'évaluation
            }
        }
    }
    $formResult['erreur'] = $erreur;
    return $formResult;
}
示例#30
0
        $cfg['deny_attribute'] = isset($cfg['deny_attribute1'][0]) ? $cfg['deny_attribute1'] : 0;
    }
    unset($cfg['deny_attribute1']);
    if (isset($cfg['tidy']) && $cfg['tidy'] == 2) {
        $cfg['tidy'] = isset($cfg['tidy2'][0]) ? $cfg['tidy2'] : 0;
    }
    unset($cfg['tidy2']);
    if (isset($cfg['unique_ids']) && $cfg['unique_ids'] == 2) {
        $cfg['unique_ids'] = isset($cfg['unique_ids2'][0]) ? $cfg['unique_ids2'] : 1;
    }
    unset($cfg['unique_ids2']);
    unset($cfg['and_mark']);
    // disabling and_mark
    $cfg['show_setting'] = 'hlcfg';
    $st = microtime();
    $out = htmLawed($_POST['text'], $cfg, $_POST['spec']);
    $et = microtime();
    echo '<br /><a href="htmLawedTest.php" title="[toggle visibility] syntax-highlighted" onclick="javascript:toggle(\'inputR\'); return false;"><span class="notice">Input code &raquo;</span></a> <span class="help" title="tags estimated as half of total &gt; and &lt; chars; values may be inaccurate for non-ASCII text"><small><big>', strlen($_POST['text']), '</big> chars, ~<big>', $tag = round((substr_count($_POST['text'], '>') + substr_count($_POST['text'], '<')) / 2), '</big> tag', $tag > 1 ? 's' : '', '</small>&nbsp;</span><div id="inputR" style="display: none;">', format($_POST['text']), '</div><script type="text/javascript">hl(\'inputR\');</script>', !isset($_POST['text'][$_hlimit]) ? ' <a href="htmLawedTest.php" title="[toggle visibility] hexdump; non-viewable characters like line-returns are shown as dots" onclick="javascript:toggle(\'inputD\'); return false;"><span class="notice">Input binary &raquo;&nbsp;</span></a><div id="inputD" style="display: none;">' . hexdump($_POST['text']) . '</div>' : '', ' <a href="htmLawedTest.php" title="[toggle visibility] finalized internal settings as interpreted by htmLawed; for developers" onclick="javascript:toggle(\'settingF\'); return false;"><span class="notice">Finalized internal settings &raquo;&nbsp;</span></a> <div id="settingF" style="display: none;">$config: ', str_replace(array('    ', "\t", '  '), array('  ', '&nbsp;  ', '&nbsp; '), nl2br(htmlspecialchars(print_r($GLOBALS['hlcfg']['config'], true)))), '<br />$spec: ', str_replace(array('    ', "\t", '  '), array('  ', '&nbsp;  ', '&nbsp; '), nl2br(htmlspecialchars(print_r($GLOBALS['hlcfg']['spec'], true)))), '</div><script type="text/javascript">hl(\'settingF\');</script>', '<br /><a href="htmLawedTest.php" title="[toggle visibility] suitable for copy-paste" onclick="javascript:toggle(\'outputF\'); return false;"><span class="notice">Output &raquo;</span></a> <span class="help" title="approx., server-specific value excluding the \'include()\' call"><small>htmLawed processing time <big>', number_format(substr($et, 0, 9) + substr($et, -10) - substr($st, 0, 9) - substr($st, -10), 4), '</big> s</small></span>', ($mem = memory_get_peak_usage()) !== false ? '<span class="help"><small>, peak memory usage <big>' . round(($mem - $pre_mem) / 1048576, 2) . '</big> <small>MB</small>' : '', '</small></span><div id="outputF"  style="display: block;"><div><textarea id="text2" class="textarea" name="text2" rows="5" cols="100" style="width: 100%;">', htmlspecialchars($out), '</textarea></div><button type="button" onclick="javascript:document.getElementById(\'text2\').focus();document.getElementById(\'text2\').select()" title="select all to copy" style="float:right;">Select all</button>';
    if ($_w3c_validate && $validation) {
        ?>
  
<button type="button" title="HTML 4.01 W3C online validation" style="float: right;" onclick="javascript: sndValidn('text2', 'html401'); return false;" onkeypress="javascript: sndValidn('text2', 'html401'); return false;">Check HTML</button>
<button type="button" title="XHTML 1.1 W3C online validation" style="float: right;" onclick="javascript: sndValidn('text2', 'xhtml110'); return false;" onkeypress="javascript: sndValidn('text2', 'xhtml110'); return false;">Check XHTML</button>
  
<?php 
    }
    echo '</div><br /><a href="htmLawedTest.php" title="[toggle visibility] syntax-highlighted" onclick="javascript:toggle(\'outputR\'); return false;"><span class="notice">Output code &raquo;</span></a><div id="outputR" style="display: block;">', format($out), '</div><script type="text/javascript">hl(\'outputR\');</script>', !isset($_POST['text'][$_hlimit]) ? ' <a href="htmLawedTest.php" title="[toggle visibility] hexdump; non-viewable characters like line-returns are shown as dots" onclick="javascript:toggle(\'outputD\'); return false;"><span class="notice">Output binary &raquo;</span></a><div id="outputD" style="display: none;">' . hexdump($out) . '</div>' : '', ' <a href="htmLawedTest.php" title="[toggle visibility] inline output-input diff; might not be perfectly accurate, semantically or otherwise " onclick="javascript:toggle(\'diff\'); diffLaunch(); return false;"><span class="notice">Diff &raquo;</span></a> <div id="diff" style="display: none;"></div><br /><a href="htmLawedTest.php" title="[toggle visibility] XHTML 1 Transitional doctype" onclick="javascript:toggle(\'outputH\'); return false;"><span class="notice">Output rendered &raquo;</span></a><div id="outputH" style="display: block;">', $out, '</div>';
} else {
    ?>

<br />