示例#1
0
 public function escapeHTML($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->escapeHtml($string);
 }
示例#2
0
 /**
  * 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;
 }
示例#3
0
 public function index01Action()
 {
     $escaper = new Escaper();
     $input = "<script>alert12</script>";
     echo $escaper->escapeHtml($input);
     return false;
 }
 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());
 }
示例#5
0
文件: AntiXSS.php 项目: hughnguy/php
 /**
  * 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.');
 }
示例#6
0
 /**
  * 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);
 }
 public function Index02Action()
 {
     /** JS SCRIPT */
     $input = '<script>alert("abc");</script>';
     $escaper = new \Zend\Escaper\Escaper();
     echo $output = $escaper->escapeHtml($input);
     return $this->response;
 }
示例#8
0
 public function __invoke($string)
 {
     $escaper = new Escaper();
     if (!preg_match('//u', $string)) {
         $string = utf8_encode($string);
     }
     $string = $escaper->escapeHtml($string);
     return $string;
 }
 /**
  * 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;
 }
示例#10
0
 /**
  *
  * @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;
 }
示例#11
0
 /**
  * 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);
 }
示例#12
0
 /**
  * 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;
 }
 /**
  * @param mixed $input
  * @return mixed
  */
 public static function escapeHtml($input)
 {
     self::init();
     return self::$escaper->escapeHtml($input);
 }
 /**
  * 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);
 }
示例#15
0
 /**
  * {@inheritdoc}
  */
 public function escapeHtml($string)
 {
     return $this->escaper->escapeHtml($string);
 }
示例#16
0
 /**
  * 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);
 }
示例#17
0
 /**
  * @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'])))];
 }