public function Index02Action() { /** JS SCRIPT */ $input = '<script>alert("abc");</script>'; $escaper = new \Zend\Escaper\Escaper(); echo $output = $escaper->escapeHtml($input); return $this->response; }
/** * Create content to write to the output file * * Uses the passed data and template to generate content. */ private function createContentFromData(array $data, string $template) : string { $escaper = new Escaper(); $strings = array_map(function ($link) use($template, $escaper) { return sprintf($template, $link['link'], $escaper->escapeHtml($link['title'])); }, $data['links']); return implode("\n", $strings); }
protected function setUp() { $this->mathRandomMock = $this->getMock('Magento\\Framework\\Math\\Random', [], [], '', false); $methods = ['setData', 'getData']; $this->sessionMock = $this->getMock('Magento\\Framework\\Session\\SessionManager', $methods, [], '', false); $this->escaperMock = $this->getMock('Magento\\Framework\\Escaper', [], [], '', false); $this->escaperMock->expects($this->any())->method('escapeHtmlAttr')->willReturnArgument(0); $this->formKey = new FormKey($this->mathRandomMock, $this->sessionMock, $this->escaperMock); }
public function __invoke($string) { $escaper = new Escaper(); if (!preg_match('//u', $string)) { $string = utf8_encode($string); } $string = $escaper->escapeHtml($string); return $string; }
public function index03Action() { $input = <<<INPUT \t\t' onmouseover='alert(/ZF2!/); INPUT; $escaper = new Escaper(); $output = $escaper->escapeHtmlAttr($input); echo "<span title='{$output}'>ZendVN</span>"; return false; }
public function Index04Action() { /** JS SCRIPT */ $input = <<<INPUT ' onmouseover='alert(/ZF2!/); INPUT; $escaper = new Escape('utf-8'); $output = $escaper->escapeHtmlAttr($input); echo '<span title=' . $output . '>Zend</span>'; return $this->response; }
/** * Create/update the response representing the error. * * @param Throwable|Exception $e * @param ServerRequestInterface $request * @param ResponseInterface $response * @return ResponseInterface */ public function __invoke($e, ServerRequestInterface $request, ResponseInterface $response) { $response = $response->withStatus(Utils::getStatusCode($e, $response)); $body = $response->getBody(); if ($this->isDevelopmentMode) { $escaper = new Escaper(); $body->write($escaper->escapeHtml((string) $e)); return $response; } $body->write($response->getReasonPhrase() ?: 'Unknown Error'); return $response; }
public function escapeURLComponent($string) { if (is_object($string) == true) { if (method_exists($string, '__toString') == false) { throw EscapeException::fromBadObject($string); } $string = (string) $string; } if (is_array($string) == true) { throw EscapeException::fromBadArray(); } return $this->zendEscape->escapeUrl($string); }
/** * @return \Zend\View\Model\ViewModel */ public function postAction() { $this->getView()->setTemplate('application/news/post'); $escaper = new Escaper('utf-8'); $post = (string) $escaper->escapeUrl($this->getParam('post')); $query = $this->getTable('SD\\Admin\\Model\\ContentTable'); $new = $query->queryBuilder()->select(['c.title, c.text, c.date, c.preview'])->from('SD\\Admin\\Entity\\Content', 'c')->where('c.type = 1 AND c.menu = 0 AND c.language = :language AND c.titleLink = :titleLink')->setParameter(':language', (int) $this->language())->setParameter(':titleLink', (string) $post)->orderBy('c.date', 'DESC')->getQuery()->getResult(); if ($new) { $this->getView()->setVariable('new', $new[0]); $this->initMetaTags($new[0]); return $this->getView(); } return $this->setErrorCode(404); }
/** * Append record id as a hash to the last search URL. * This way the previus window scroll position gets restored * when the user returns to search results from a record page. * * @return void */ protected function modifyLastSearchURL() { $memory = $this->getServiceLocator()->get('VuFind\\Search\\Memory'); if ($last = $memory->retrieve()) { $parts = parse_url($last); // Do not overwrite existing hash if (!isset($parts['fragment'])) { $escaper = new Escaper('utf-8'); $id = $this->driver->getUniqueId(); $id = $escaper->escapeUrl($id); $last .= "#{$id}"; $memory->rememberSearch($last); } } }
/** * Escapes strings based on context * @param string $string The string to escape * @param int $context The context to escape in * @return string The escaped string * @throws \InvalidArgumentException If the context is invalid */ public function escape($string, $context = self::HTML_BODY) { $type = gettype($string); if (in_array($type, array('boolean', 'integer', 'double', 'NULL'), true)) { return $string; } if (in_array($type, array('object', 'resource', 'unknown type'), true)) { throw new \InvalidArgumentException("Unable to escape variable of type {$type}."); } if ($context === self::HTML_STRING) { return parent::escapeHtml($string); } if ($context === self::HTML_ATTR) { return parent::escapeHtmlAttr($string); } if ($context === self::CSS) { return parent::escapeCss($string); } if ($context === self::JS_STRING) { return parent::escapeJs($string); } if ($context === self::URL_PARAM) { return parent::escapeUrl($string); } throw new \InvalidArgumentException('Invalid context.'); }
/** * Debug helper function. This is a wrapper for var_dump() that adds * the <pre /> tags, cleans up newlines and indents, and runs * htmlentities() before output. * * @param mixed $var The variable to dump. * @param string $label OPTIONAL Label to prepend to output. * @param bool $echo OPTIONAL Echo output if true. * @return string */ public static function dump($var, $label = null, $echo = true) { // format the label $label = $label === null ? '' : rtrim($label) . ' '; // var_dump the variable into a buffer and keep the output ob_start(); var_dump($var); $output = ob_get_clean(); // neaten the newlines and indents $output = preg_replace("/\\]\\=\\>\n(\\s+)/m", "] => ", $output); if (static::getSapi() == 'cli') { $output = PHP_EOL . $label . PHP_EOL . $output . PHP_EOL; } else { if (null !== static::$escaper) { $output = static::$escaper->escapeHtml($output); } elseif (!extension_loaded('xdebug')) { $output = static::getEscaper()->escapeHtml($output); } $output = '<pre>' . $label . $output . '</pre>'; } if ($echo) { echo $output; } return $output; }
/** * Builds menu HTML. * * @method getMenus * * @param int $parent * @param array $menu * * @return string generated html code */ private function getMenus($parent = 0, array $menu = []) { $output = ''; if (isset($menu['submenus'][$parent])) { $escaper = new Escaper('utf-8'); foreach ($menu['submenus'][$parent] as $id) { $output .= "<ul class='table-row'>"; $output .= "<li class='table-cell flex-2'>" . $menu['menus'][$id]->getCaption() . '</li>'; $output .= "<li class='table-cell flex-b'><a title='" . $this->translate('DETAILS') . "' hreflang='" . $this->language('languageName') . "' itemprop='url' href='/admin/menu/detail/" . $escaper->escapeUrl($menu['menus'][$id]->getId()) . "' class='btn btn-sm blue'><i class='fa fa-info'></i></a></li>"; $output .= "<li class='table-cell flex-b'><a title='" . $this->translate('EDIT') . "' hreflang='" . $this->language('languageName') . "' itemprop='url' href='/admin/menu/edit/" . $escaper->escapeUrl($menu['menus'][$id]->getId()) . "' class='btn btn-sm orange'><i class='fa fa-pencil'></i></a></li>"; if (0 === $menu['menus'][$id]->isActive()) { $output .= "<li class='table-cell flex-b'><a title='" . $this->translate('DEACTIVATED') . "' hreflang='" . $this->language('languageName') . "' itemprop='url' href='/admin/menu/activate/" . $escaper->escapeUrl($menu['menus'][$id]->getId()) . "' class='btn btn-sm deactivated'><i class='fa fa-minus-square-o'></i></a></li>"; } else { $output .= "<li class='table-cell flex-b'><a title='" . $this->translate('ACTIVE') . "' hreflang='" . $this->language('languageName') . "' itemprop='url' href='/admin/menu/deactivate/" . $escaper->escapeUrl($menu['menus'][$id]->getId()) . "' class='btn btn-sm active'><i class='fa fa fa-check-square-o'></i></a></li>"; } $output .= "\n <li class='table-cell flex-b'>\n <button role='button' aria-pressed='false' aria-label='" . $this->translate('DELETE') . "' id='" . $menu['menus'][$id]->getId() . "' type='button' class='btn btn-sm delete dialog_delete' title='" . $this->translate('DELETE') . "'><i class='fa fa-trash-o'></i></button>\n <div role='alertdialog' aria-labelledby='dialog" . $menu['menus'][$id]->getId() . "Title' class='delete_" . $menu['menus'][$id]->getId() . " dialog_hide'>\n <p id='dialog" . $menu['menus'][$id]->getId() . "Title'>" . $this->translate('DELETE_CONFIRM_TEXT') . ' «' . $menu['menus'][$id]->getCaption() . "»</p>\n <ul>\n <li>\n <a class='btn delete' href='/admin/menu/delete/" . $escaper->escapeUrl($menu['menus'][$id]->getId()) . "'><i class='fa fa-trash-o'></i> " . $this->translate('DELETE') . "</a>\n </li>\n <li>\n <button role='button' aria-pressed='false' aria-label='" . $this->translate('CANCEL') . "' class='btn btn-default cancel'><i class='fa fa-times'></i> " . $this->translate('CANCEL') . '</button> </li> </ul> </div> </li>'; $output .= '</ul>'; $output .= $this->getMenus($id, $menu); } } return $output; }
public function testInvokingWithExceptionAndNoEnvironmentModeSetDoesNotIncludeTraceInResponseBody() { $error = new Exception('foo', 400); $response = call_user_func($this->final, $this->request, $this->response, $error); $expected = $this->escaper->escapeHtml($error->getTraceAsString()); $this->assertNotContains($expected, (string) $response->getBody()); }
/** * * @todo Chenge format of JSON response from [{}] to {} for one row response? * @todo Add develope mode for debug with HTML POST and GET * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable|null $next * @return ResponseInterface * @throws \zaboy\rest\RestException */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $responseBody = $request->getAttribute('Response-Body'); $accept = $request->getHeaderLine('Accept'); if (isset($accept) && preg_match('#^application/([^+\\s]+\\+)?json#', $accept)) { $status = $response->getStatusCode(); $headers = $response->getHeaders(); $response = new JsonResponse($responseBody, $status, $headers); } else { $escaper = new Escaper(); $result = ''; switch (true) { case gettype($responseBody) == 'array': // foreach ($responseBody as $valueArray) { // $result = $result . ' - '; // if (is_array($valueArray)) { // foreach ($valueArray as $key => $value) { // $result = $result // . $escaper->escapeHtml($key) // . ' - ' // . $escaper->escapeHtml(is_array($value) ? print_r($value, true) : $value) // . '; _ _ '; // } // $result = $result . '<br>' . PHP_EOL; // } else { // $result = $result . $escaper->escapeHtml($valueArray) . '<br>' . PHP_EOL; // } // } $result = '<pre>' . $escaper->escapeHtml(print_r($responseBody, true)) . '</pre>'; break; case is_numeric($responseBody) or is_string($responseBody): $result = $responseBody . '<br>' . PHP_EOL; break; case is_bool($responseBody): $result = $responseBody ? 'TRUE' : 'FALSE'; $result = $result . '<br>' . PHP_EOL; break; default: throw new \zaboy\rest\RestException('$responseBody must be array, numeric or bool. But ' . gettype($responseBody) . ' given.'); } $response->getBody()->write($result); } if ($next) { return $next($request, $response); } return $response; }
/** * Shorthand method for getting params from URLs. Makes code easier to edit and avoids DRY code. * * @param string $paramName * * @return array|string */ public function __invoke($paramName) { $escaper = new Escaper('utf-8'); /* * Return early. Usually params will come from post. * * @var mixed */ $param = $this->params->fromPost($paramName, null); if (!$param) { $param = $this->findParam($paramName); } /* * If this is array it MUST comes from fromFiles() */ if (is_array($param) && !empty($param)) { return $param; } return $escaper->escapeHtml($param); }
/** * Closes the table by printing a </table> statement */ protected function printTableEnd() { $html = '</table>'; // Any current column settings? pass them in the form if (in_array('simpleSearch', $this->displaySettings)) { if (isset($_GET['columns'])) { $value = $_GET['columns']; if (is_array($_GET['columns'])) { $value = '['; foreach ($_GET['columns'] as $column) { $value .= '"' . $column . '",'; } $value = rtrim($value, ",") . ']'; } $html .= sprintf("<input type='hidden' name='columns' value='%s'/>", $this->escaper->escapeHtmlAttr($value)); } if (isset($_GET['sort']) && isset($_GET['order'])) { $html .= "<input type='hidden' name='sort' value='" . $this->escaper->escapeHtmlAttr($_GET['sort']) . "' />"; $html .= "<input type='hidden' name='order' value='" . $this->escaper->escapeHtmlAttr($_GET['order']) . "' />"; } $html .= '</form>'; } return $html; }
/** * Escapes strings to make them safe for use * within HTML templates. Used by the auto-escaping * functionality in setVar() and available to * use within your views. * * Uses ZendFramework's Escaper to handle the actual escaping, * based on context. Valid contexts are: * - html * - htmlAttr * - js * - css * - url * * References: * - https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet * - http://framework.zend.com/manual/current/en/modules/zend.escaper.introduction.html * * @param $data * @param $context * @param escaper // An instance of ZF's Escaper to avoid repeated class instantiation. * * @return string */ function esc($data, $context = 'html', $escaper = null) { if (is_array($data)) { foreach ($data as $key => &$value) { $value = esc($value, $context); } } $context = strtolower($context); if (!is_object($escaper)) { $escaper = new Escaper(config_item('charset')); } // Valid context? if (!in_array($context, ['html', 'htmlattr', 'js', 'css', 'url'])) { throw new \InvalidArgumentException('Invalid Context type: ' . $context); } if (!is_string($data)) { return $data; } switch ($context) { case 'html': $data = $escaper->escapeHtml($data); break; case 'htmlattr': $data = $escaper->escapeHtmlAttr($data); break; case 'js': $data = $escaper->escapeJs($data); break; case 'css': $data = $escaper->escapeCss($data); break; case 'url': $data = $escaper->escapeUrl($data); break; default: break; } return $data; }
/** * Create a complete error message for development purposes. * * Creates an error message with full error details: * * - If the error is an exception, creates a message that includes the full * stack trace. * - If the error is an object that defines `__toString()`, creates a * message by casting the error to a string. * - If the error is not an object, casts the error to a string. * - Otherwise, cerates a generic error message indicating the class type. * * In all cases, the error message is escaped for use in HTML. * * @param mixed $error * @return string */ private function createDevelopmentErrorMessage($error) { if ($error instanceof Exception) { $message = $error->getMessage() . "\n"; $message .= $error->getTraceAsString(); } elseif (is_object($error) && !method_exists($error, '__toString')) { $message = sprintf('Error of type "%s" occurred', get_class($error)); } else { $message = (string) $error; } $escaper = new Escaper(); return $escaper->escapeHtml($message); }
/** * Get escaper, and escape HTML content if specified * * @param string|null $content * @return Escaper|string */ public function escape($content = null) { $escaper = new Escaper(Pi::service('i18n')->charset); if (null === $content) { return $escaper; } return $escaper->escapeHtml($content); }
/** * @param Invoice $invoice * @return string[] */ public function format(Invoice $invoice) { $statusFormat = static::$statusMap[$invoice->getStatus()]; return [sprintf('<span class="label label-%s">%s</span>', $statusFormat['class'], $this->escaper->escapeHtml($statusFormat['label'])), sprintf('%s<br /><small>%s</small>', $this->escaper->escapeHtml($this->dateFormatter->format($invoice->getIssueDate())), $this->escaper->escapeHtml($this->getIssueDateAddition($invoice))), $invoice->getInvoiceNumber(), $this->escaper->escapeHtml($invoice->getClient()->getName()), $this->escaper->escapeHtml($this->numberFormatter->formatCurrency($invoice->getTotalAmount(), $invoice->getCurrencyCode())), sprintf('<a href="%s" class="btn btn-xs btn-default">Show</a>', $this->escaper->escapeHtmlAttr($this->router->assemble(['invoiceId' => $invoice->getId()], ['name' => 'invoices/show'])))]; }
/** * @param mixed $input * @return mixed */ public static function escapeUrl($input) { self::init(); return self::$escaper->escapeUrl($input); }
/** * Set Escaper instance * * @param Escaper $escaper * @return AbstractStandalone */ public function setEscaper(Escaper $escaper) { $encoding = $escaper->getEncoding(); $this->escapers[$encoding] = $escaper; return $this; }
/** * {@inheritdoc} */ public function escapeUrl($string) { return $this->escaper->escapeUrl($string); }
public function setEscaper(Escaper\Escaper $escaper) { $this->escaper = $escaper; $this->encoding = $escaper->getEncoding(); return $this; }
/** * * Escapes values in an array and all its sub-arrays. * * @param array $data Array of data to be escaped. This array will be modifed during the escape operation. * * @param string $escape_encoding Encoding to be used for escaping data values in $data and $this->data. * If this value is empty, the value of $this->escape_encoding will be used * if it's not empty, else the default value of 'utf-8' will be finally used. * See documentation for $this->escape_encoding for more info. * * @param array $data_vars_2_html_escape An array of keys in $data whose values (only strings) will be * individually escaped using Zend\Escaper\Escaper::escapeHtml($string). * * @param array $data_vars_2_html_attr_escape An array of keys in $data whose values (only strings) will be * individually escaped using Zend\Escaper\Escaper::escapeHtmlAttr($string). * * @param array $data_vars_2_css_escape An array of keys in $data whose values (only strings) will be * individually escaped using Zend\Escaper\Escaper::escapeCss($string). * * @param array $data_vars_2_js_escape An array of keys in $data whose values (only strings) will be * individually escaped using Zend\Escaper\Escaper::escapeJs($string). * * @param \Zend\Escaper\Escaper $escaper An optional escaper object that will be used for escaping. * * @return void * * @throws \Rotexsoft\FileRenderer\FileNotFoundException */ protected function escapeData(array &$data, $escape_encoding = 'utf-8', array $data_vars_2_html_escape = array(), array $data_vars_2_html_attr_escape = array(), array $data_vars_2_css_escape = array(), array $data_vars_2_js_escape = array(), \Zend\Escaper\Escaper $escaper = null) { if (count($data) <= 0) { //no data supplied; nothing to do return; } else { if (count($data_vars_2_html_escape) <= 0 && count($data_vars_2_html_attr_escape) <= 0 && count($data_vars_2_css_escape) <= 0 && count($data_vars_2_js_escape) <= 0) { //no field has been specified for escaping; nothing to do return; } } $hash_of_data_array = spl_object_hash(json_decode(json_encode($data))); if (array_key_exists($hash_of_data_array, $this->multi_escape_prevention_guard) && $this->multi_escape_prevention_guard[$hash_of_data_array]['escape_encoding'] === $escape_encoding && $this->multi_escape_prevention_guard[$hash_of_data_array]['data_vars_2_html_escape'] === $data_vars_2_html_escape && $this->multi_escape_prevention_guard[$hash_of_data_array]['data_vars_2_html_attr_escape'] === $data_vars_2_html_attr_escape && $this->multi_escape_prevention_guard[$hash_of_data_array]['data_vars_2_css_escape'] === $data_vars_2_css_escape && $this->multi_escape_prevention_guard[$hash_of_data_array]['data_vars_2_js_escape'] === $data_vars_2_js_escape) { //the data array has already been escaped; don't wanna escape already escaped data return; } $final_encoding = empty($escape_encoding) ? empty($this->escape_encoding) ? 'utf-8' : $this->escape_encoding : $escape_encoding; if (is_null($escaper)) { if ($this->escaper instanceof \Zend\Escaper\Escaper && $this->escaper->getEncoding() === $final_encoding) { $escaper = $this->escaper; //we can safely use the escaper associated with this class. } else { $escaper = new \Zend\Escaper\Escaper($final_encoding); } } foreach ($data as $key => $value) { $methods = array(); if (in_array($key, $data_vars_2_html_escape) || in_array('*', $data_vars_2_html_escape)) { $methods[] = 'escapeHtml'; } if (in_array($key, $data_vars_2_html_attr_escape) || in_array('*', $data_vars_2_html_attr_escape)) { $methods[] = 'escapeHtmlAttr'; } if (in_array($key, $data_vars_2_css_escape) || in_array('*', $data_vars_2_css_escape)) { $methods[] = 'escapeCss'; } if (in_array($key, $data_vars_2_js_escape) || in_array('*', $data_vars_2_js_escape)) { $methods[] = 'escapeJs'; } if (count($methods) > 0 || is_array($data[$key])) { if (is_array($data[$key])) { // recursively escape sub-array $this->escapeData($data[$key], $final_encoding, $data_vars_2_html_escape, $data_vars_2_html_attr_escape, $data_vars_2_css_escape, $data_vars_2_js_escape, $escaper); } else { if (is_string($data[$key])) { foreach ($methods as $method) { // escape the value $data[$key] = $escaper->{$method}($data[$key]); } } } //if( is_array($data[$key]) ) ... else if( is_string($data[$key]) ) } // if( count($methods) > 0 || is_array($data[$key]) ) } // foreach( $data as $key => $value ) //add the hash of the data array we have just escaped to the list of //hashes of escaped data arrays $hash_of_escaped_data_array = spl_object_hash(json_decode(json_encode($data))); $this->multi_escape_prevention_guard[$hash_of_escaped_data_array] = array('escape_encoding' => $escape_encoding, 'data_vars_2_html_escape' => $data_vars_2_html_escape, 'data_vars_2_html_attr_escape' => $data_vars_2_html_attr_escape, 'data_vars_2_css_escape' => $data_vars_2_css_escape, 'data_vars_2_js_escape' => $data_vars_2_js_escape); }