function actionSearch($q = null, $page = 1) { $pages = new CPagination(); $pages->pageSize = 50; $pages->currentPage = $page; $p = new CHtmlPurifier(); $q = CHtml::encode($p->purify($q)); $searchCriteria = new stdClass(); $searchCriteria->select = 'id'; $searchCriteria->query = $q . '*'; $searchCriteria->paginator = $pages; $searchCriteria->from = join(",", $this->indexes); // Получаем данные в виде массива $resArray = Yii::App()->search->searchRaw($searchCriteria); $news = null; if (is_array($resArray['matches'])) { $c = new CDbCriteria(); $c->order = 'FIELD(id,' . join(",", array_keys($resArray['matches'])) . ')'; $news = News::model()->findAllByPk(array_keys($resArray['matches']), $c); } $this->render("search_results", array('news' => $news)); }
/** * 对内容进行过滤 未使用 */ public static function htmlPurifier($content) { $p = new CHtmlPurifier(); //过滤规则 $p->options = array('URI.Disable' => true); return $p->purify($content); }
public function Purify($value) { $p = new CHtmlPurifier(); $p->options = array('HTML.Allowed' => 'strong,em,u,h1,h2,h3,h4'); $cleanHtml = $p->purify($value); return $cleanHtml; }
/** * @param \Solarium\QueryType\Select\Result\Result $ergebnisse * @return array(); */ public static function ergebnisse2FeedData($ergebnisse) { $data = array(); $dokumente = $ergebnisse->getDocuments(); $highlighting = $ergebnisse->getHighlighting(); $purifier = new CHtmlPurifier(); $purifier->options = array('URI.AllowedSchemes' => array('http' => true, 'https' => true)); foreach ($dokumente as $dokument) { $model = Dokument::getDocumentBySolrId($dokument->id); $risitem = $model->getRISItem(); if (!$risitem) { continue; } $link = $risitem->getLink(); $highlightedDoc = $highlighting->getResult($dokument->id); $item = array("title" => $model->name . " (zu " . $risitem->getTypName() . " \"" . $risitem->getName() . "\"", "link" => $link, "content" => "", "dateCreated" => RISTools::date_iso2timestamp(str_replace("T", " ", str_replace("Z", "", $dokument->sort_datum))), "aenderung_guid" => $link); if ($highlightedDoc && count($highlightedDoc) > 0) { foreach ($highlightedDoc as $highlight) { $item["content"] .= $purifier->purify(implode(' (...) ', $highlight)) . '<br/>'; } } $data[] = $item; } return $data; }
public function safehtml($attr, $params) { $p = new CHtmlPurifier(); $p->options = Yii::app()->params["HTMLPurifierOptions"]; $p->options["HTML.Allowed"] = "a[href],b,strong,i,em,u,small,sub,sup"; $this->{$attr} = trim($p->purify($this->{$attr})); }
public function safeTransform($content) { $content = $this->transform($content); $purifier = new CHtmlPurifier(); $purifier->options = $this->purifierOptions; return $purifier->purify($content); }
public function purifyText($attribute, $params) { $module = Yii::app()->getModule('comment'); $p = new CHtmlPurifier(); $p->options = ['HTML.Allowed' => $module->allowedTags]; $this->{$attribute} = $p->purify($this->{$attribute}); }
/** * Manage the created fields */ public function beforeSave() { if ($this->isNewRecord) { $this->created = time(); } $p = new CHtmlPurifier(); $this->subject = $p->purify($this->subject); return parent::beforeSave(); }
public function actionHtmlFilter() { $str = "fd'<script><b>fdsafds</b>alert('good')</script>d%#sds/ds\gs<a href='fdsa'>fdas</a>a@fd<b>fdsa<?php echo 'fdsad'; ?>fds</b>sa0"; $p = new CHtmlPurifier(); echo $p->processOutput($str); /* echo $p->purify($str); */ }
/** * Process a string with markup * * @abstract * @param string $input * @return string $output */ public function process($input) { $out = $this->processMarkup($input); if ($this->purify) { $purifier = new CHtmlPurifier(); $out = $purifier->purify($out); } return $out; }
/** * Processes the captured output. * This method converts the content in markdown syntax to HTML code. * If {@link purifyOutput} is true, the HTML code will also be purified. * @param string $output the captured output to be processed * @see convert */ public function processOutput($output) { $output = $this->transform($output); if ($this->purifyOutput) { $purifier = new CHtmlPurifier(); $output = $purifier->purify($output); } parent::processOutput($output); }
/** * @return array validation rules for model attributes. * @internal you should only define rules for those attributes that will receive user inputs */ public function rules() { // On ajoute un filtre CHtmlPurifier avant l'enregistrement des données. Il sert ici moins à la protection contre // les attaques XSS qu'à s'assurer que le code HTML de l'actualité est valide. // Cette condition est indispensable pour que la classe DOMHelper puisse tronquer correctement // le texte pour construire des résumés (en page d'accueil par exemple) $htmlPurifier = new CHtmlPurifier(); $htmlPurifier->setOptions(array('HTML.SafeIframe' => true, 'URI.SafeIframeRegexp' => '%www.youtube.com/embed/%')); return array(array('news_id, language_id, title', 'required'), array('title, description, keywords', 'length', 'max' => 255), array('language_id', 'exist', 'attributeName' => 'id', 'className' => 'Language'), array('news_id', 'exist', 'attributeName' => 'id', 'className' => 'News'), array('content', 'filter', 'filter' => array($htmlPurifier, 'purify')), array('tagsString', 'length', 'max' => 255), array('created_at, updated_at', 'safe'), array('news_id, language_id, title, slug, description, keywords, content, tagsString, tagIdFilter, enabled, eventDate', 'safe', 'on' => 'search')); }
public static function filterString($string) { $string = strip_tags($string); $string = stripcslashes($string); $string = htmlspecialchars($string); $p = new CHtmlPurifier(); $string = $p->purify($string); $string = addslashes($string); $string = str_replace("\r\n", "\n", $string); return $string; }
public function run() { $this->markdown = CHtml::encode($this->markdown); $parserClass = $this->parserClass; $parser = new $parserClass(); $html = $parser->parse($this->markdown); if ($this->purifyOutput) { $purifier = new CHtmlPurifier(); $html = $purifier->purify($html); } $this->render('markdownView', array('content' => $html)); }
public function actionHtmlPurifier() { $user_input = null; if (isset($_POST['user_input'])) { $user_input = $_POST['user_input']; } $parser = new CHtmlPurifier(); //create instance of CHtmlPurifier $user_input = $parser->purify($user_input); //we purify the $user_input $this->render("htmlpurifier", array('user_input' => $user_input)); }
protected function purifyHtml($html) { // remove bad parsing $html = preg_replace('#\\\\r\\\\n|\\\\r|\\\\n|\\\\#sui', '', $html); $p = new CHtmlPurifier(); $p->options = array('HTML.Allowed' => 'img[src],p,br,b,strong,i'); $html = $p->purify($html); $p->options = array('HTML.Allowed' => ''); $text = $p->purify($html); if (mb_strlen($text, 'UTF-8') === mb_strlen($html, 'UTF-8')) { return '<pre>' . $text . '</pre>'; } return $html; }
public function purify($value) { $p = new CHtmlPurifier(); $p->options = array('HTML.Allowed' => 'b,p,br'); $cleanHtml = $p->purify($value); return $cleanHtml; }
/** * @param $action */ private function savePage($action) { //var_dump($_POST); die; Yii::log("Function SavePage DesignController called", "trace", self::LOG_CAT); $model = DocPages::model()->findByPk($_POST['pageId']); if (isset($_POST['desContent'])) { $purifier = new CHtmlPurifier(); $model->docData = $purifier->purify($_POST['desContent']); if ($model->update()) { Yii::app()->user->setFlash('success', 'The page was updated successfully'); $this->redirect($action); return; } } Yii::app()->user->setFlash('error', 'The page was not updated successfully, contact your administrator'); $this->redirect($action); return; }
protected function preFilter($filterChain) { // logic being applied before the action is executed if (isset($_POST) && count($_POST) > 0) { $obj = new CHtmlPurifier(); $obj->options = array('HTML.Allowed' => 'p,b,u,a[href|title],i,img[src|alt|title],em,strong,strike,ul,ol,li,div[align],br', 'CSS.AllowedProperties' => array('text-decoration' => true, 'font-family' => true, 'font-size' => true, 'text-align' => true, 'padding-left' => true, 'padding-right' => true, 'padding-top' => true, 'padding-bottom' => true, 'color' => true, 'background-color' => true), 'AutoFormat.RemoveEmpty' => true); foreach ($_POST as $key => $val) { if (is_array($val)) { $val = $obj->purify($val); //$_POST[$key] = Yii::app()->input->xssClean($val); $_POST[$key] = Yii::app()->input->xssClean($this->filterSubElement($val, $obj)); } else { $_POST[$key] = $obj->purify($val); } } } $filterChain->run(); // return true; // false if the action should not be executed }
public function actionRoom($room_id) { $since = intval(isset($_POST["since"]) ? $_POST["since"] : $_GET["since"]); $room_id = (int) $room_id; $key = "chat{$room_id}"; $room = Yii::app()->cache->get($key); if (!is_array($room)) { $room = []; } if (Yii::app()->request->isPostRequest) { $msg = trim($_POST["msg"]); $h = date("h"); $m = date("i"); if ($h == 4 && $m >= 20 && $m <= 40) { $p = new CHtmlPurifier(); $p->options = Yii::app()->params["HTMLPurifierOptions"]; $msg = trim($p->purify($msg)); } else { $msg = strip_tags($msg); } if ($msg != "") { $msg = mb_substr($msg, 0, 2048); $msg = Yii::app()->parser->parse($msg); $line = ["u" => Yii::app()->user->login, "i" => Yii::app()->user->id, "t" => time(), "m" => $msg]; array_push($room, $line); if (count($room) > 50) { array_shift($room); } } Yii::app()->cache->set($key, $room, 60 * 60 * 24 * 3); } if ($since > 0) { $roomGood = []; foreach ($room as $k => $v) { $room["m"] .= " <small>(after {$since})</small>"; if ($v["t"] > $since) { $roomGood[] = $room[$k]; } } $room = $roomGood; } echo json_encode(["room" => $room, "servertime" => time()]); }
/** * @param $action */ public static function savePage($action) { //var_dump($_POST); die; Yii::log("Function SavePage called", "trace", self::LOG_CAT); $model = DocPages::model()->findByPk($_POST['pageId']); if (isset($_POST['survContent'])) { $purifier = new CHtmlPurifier(); $purifier->options = ['URI.AllowedSchemes' => ['http' => true, 'https' => true], 'Attr.AllowedFrameTargets' => ['_blank', '_self'], 'HTML.AllowedAttributes' => ['img.src', 'a.id', 'a.name', 'a.href', 'a.target', 'span.style']]; // echo $_POST['survContent']; $model->docData = $purifier->purify($_POST['survContent']); // echo $model->docData; die; if ($model->update()) { Yii::app()->user->setFlash('success', 'The page was updated successfully'); Yii::app()->request->redirect($action); return; } } Yii::app()->user->setFlash('error', 'The page was not updated successfully, contact your administrator'); Yii::app()->request->redirect($action); return; }
/** * Required POSTED data are : * phone_number - required - number * dispo_name - required - any * @return void */ public function actionSave() { header("Content-Type: application/json"); $returnResult = ['status' => "", 'message' => ""]; $p = new CHtmlPurifier(); $disposaleForm = new DisposaleForm(); $disposaleForm->dispo_name = $p->purify(@$_POST['dispo_name']); $disposaleForm->phone_number = $p->purify(@$_POST['phone_number']); $disposaleForm->posted_data = json_encode(@$_POST); if ($disposaleForm->validate()) { if ($disposaleForm->save()) { $returnResult['status'] = 'success'; $returnResult['message'] = "New dispo sale saved"; } else { $returnResult['status'] = 'failed'; $returnResult['message'] = CHtml::errorSummary($disposaleForm); } } else { $returnResult['status'] = 'failed'; $returnResult['message'] = CHtml::errorSummary($disposaleForm); } echo json_encode($returnResult); }
/** * Получаем текст, при необходимости обрезаем: * * @param mixed $size - максимальная длина * * @return string */ public function getText($size = false) { if (false === $size || $size > mb_strlen($this->text)) { return $this->text; } $p = new CHtmlPurifier(); return $p->purify(mb_substr($this->text, 0, $size) . '...'); }
/** * Remove any script or dangerous HTML * * @param string $value */ public function xssFilter($value) { $filter = new CHtmlPurifier(); $filter->options = array('AutoFormat.RemoveEmpty' => false, 'Core.NormalizeNewlines' => false, 'CSS.AllowTricky' => true, 'HTML.SafeObject' => true, 'Output.FlashCompat' => true, 'Attr.EnableID' => true, 'Attr.AllowedFrameTargets' => array('_blank', '_self'), 'URI.AllowedSchemes' => array('http' => true, 'https' => true, 'mailto' => true, 'ftp' => true, 'nntp' => true, 'news' => true)); // To allow script BUT purify : HTML.Trusted=true (plugin idea for admin or without XSS filtering ?) /** Start to get complete filtered value with url decode {QCODE} (bug #09300). This allow only question number in url, seems OK with XSS protection **/ $sFiltered = preg_replace('#%7B([a-zA-Z0-9\\.]*)%7D#', '{$1}', $filter->purify($value)); Yii::import('application.helpers.expressions.em_core_helper'); // Already imported in em_manager_helper.php ? $oExpressionManager = new ExpressionManager(); /** We get 2 array : one filtered, other unfiltered **/ $aValues = $oExpressionManager->asSplitStringOnExpressions($value); // Return array of array : 0=>the string,1=>string length,2=>string type (STRING or EXPRESSION) $aFilteredValues = $oExpressionManager->asSplitStringOnExpressions($sFiltered); // Same but for the filtered string $bCountIsOk = count($aValues) == count($aFilteredValues); /** Construction of new string with unfiltered EM and filtered HTML **/ $sNewValue = ""; foreach ($aValues as $key => $aValue) { if ($aValue[2] == "STRING") { $sNewValue .= $bCountIsOk ? $aFilteredValues[$key][0] : $filter->purify($aValue[0]); } else { $sExpression = trim($aValue[0], '{}'); $sNewValue .= "{"; $aParsedExpressions = $oExpressionManager->Tokenize($sExpression, true); foreach ($aParsedExpressions as $aParsedExpression) { if ($aParsedExpression[2] == 'DQ_STRING') { $sNewValue .= "\"" . $filter->purify($aParsedExpression[0]) . "\""; } elseif ($aParsedExpression[2] == 'SQ_STRING') { $sNewValue .= "'" . $filter->purify($aParsedExpression[0]) . "'"; } else { $sNewValue .= $aParsedExpression[0]; } } $sNewValue .= "}"; } } gc_collect_cycles(); // To counter a high memory usage of HTML-Purifier return $sNewValue; }
public function validateBody($attr, $params) { $p = new CHtmlPurifier(); $p->options = Yii::app()->params["HTMLPurifierOptions"]; $this->{$attr} = trim($p->purify($this->{$attr})); }
function XSSFilterArray(&$array) { if (Yii::app()->getConfig('filterxsshtml') && !Permission::model()->hasGlobalPermission('superadmin', 'read')) { $filter = new CHtmlPurifier(); $filter->options = array('URI.AllowedSchemes' => array('http' => true, 'https' => true)); foreach ($array as &$value) { $value = $filter->purify($value); } } }
/** * @inheritDoc IFieldType::prepValueFromPost() * * @param mixed $value * * @return mixed */ public function prepValueFromPost($value) { // Temporary fix (hopefully) for a Redactor bug where some HTML will get submitted when the field is blank, // if any text was typed into the field, and then deleted if ($value == '<p><br></p>') { $value = ''; } if ($value) { // Swap any pagebreak <hr>'s with <!--pagebreak-->'s $value = preg_replace('/<hr class="redactor_pagebreak".*?>/', '<!--pagebreak-->', $value); if ($this->getSettings()->purifyHtml) { $purifier = new \CHtmlPurifier(); $purifier->setOptions(array('Attr.AllowedFrameTargets' => array('_blank'), 'HTML.AllowedComments' => array('pagebreak'))); $value = $purifier->purify($value); } if ($this->getSettings()->cleanupHtml) { // Remove <span> and <font> tags $value = preg_replace('/<(?:span|font)\\b[^>]*>/', '', $value); $value = preg_replace('/<\\/(?:span|font)>/', '', $value); // Remove inline styles $value = preg_replace('/(<(?:h1|h2|h3|h4|h5|h6|p|div|blockquote|pre|strong|em|b|i|u|a)\\b[^>]*)\\s+style="[^"]*"/', '$1', $value); // Remove empty tags $value = preg_replace('/<(h1|h2|h3|h4|h5|h6|p|div|blockquote|pre|strong|em|a|b|i|u)\\s*><\\/\\1>/', '', $value); } } // Find any element URLs and swap them with ref tags $value = preg_replace_callback('/(href=|src=)([\'"])[^\'"]+?#(\\w+):(\\d+)(:' . HandleValidator::$handlePattern . ')?\\2/', function ($matches) { return $matches[1] . $matches[2] . '{' . $matches[3] . ':' . $matches[4] . (!empty($matches[5]) ? $matches[5] : ':url') . '}' . $matches[2]; }, $value); return $value; }
/** * 格式化内容 */ static function formatHtml($content, $options = '') { $purifier = new CHtmlPurifier(); if ($options != false) { $purifier->options = $options; } return $purifier->purify($content); }
function XSSFilterArray(&$array) { if (Yii::app()->getConfig('filterxsshtml') && Yii::app()->session['USER_RIGHT_SUPERADMIN'] != 1) { $filter = new CHtmlPurifier(); $filter->options = array('URI.AllowedSchemes' => array('http' => true, 'https' => true)); foreach ($array as &$value) { $value = $filter->purify($value); } } }
/** * * Add answer to PDF * * @param $sQuestion - Question field text array * @param $sResponse - Answer field text array * @param $bReplaceExpressions - Try to replace LimeSurvey Expressions. This is false when exporting answers PDF from admin GUI * because we can not interpret expressions so just purify. * TODO: Find a universal valid method to interpret expressions * @param $bAllowBreakPage - Allow break cell in two pages * @return unknown_type */ function addAnswer($sQuestion, $sResponse, $bReplaceExpressions = true, $bAllowBreakPage = false) { $oPurifier = new CHtmlPurifier(); $sQuestionHTML = str_replace('-oth-', '', $sQuestion); // Copied from Writer::stripTagsFull. Really necessary? $sQuestionHTML = html_entity_decode(stripJavaScript($oPurifier->purify($sQuestionHTML)), ENT_COMPAT); if ($bReplaceExpressions) { $sData['thissurvey'] = $this->_aSurveyInfo; $sQuestionHTML = templatereplace($sQuestionHTML, array(), $sData, '', $this->_aSurveyInfo['anonymized'] == "Y", NULL, array(), true); } $sResponse = flattenText($sResponse, false, true, 'UTF-8', false); $startPage = $this->getPage(); $this->startTransaction(); $this->SetFontSize($this->_ibaseAnswerFontSize); $this->WriteHTMLCell(0, $this->_iCellHeight, $this->getX(), $this->getY(), $sQuestionHTML, 1, 1, true, true, 'L'); $this->MultiCell(0, $this->_iCellHeight, $sResponse, 1, 'L', 0, 1, '', '', true); $this->ln(2); if ($this->getPage() != $startPage && !$bAllowBreakPage) { $this->rollbackTransaction(true); $this->AddPage(); $this->addAnswer($sQuestion, $sResponse, $bReplaceExpressions, true); // "Last param = true" prevents an endless loop if a cell is longer than a page } else { $this->commitTransaction(); } }