public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)) { /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml>\n\t\t\t\t\t\t\t<ToUserName><![CDATA[%s]]></ToUserName>\n\t\t\t\t\t\t\t<FromUserName><![CDATA[%s]]></FromUserName>\n\t\t\t\t\t\t\t<CreateTime>%s</CreateTime>\n\t\t\t\t\t\t\t<MsgType><![CDATA[%s]]></MsgType>\n\t\t\t\t\t\t\t<Content><![CDATA[%s]]></Content>\n\t\t\t\t\t\t\t<FuncFlag>0</FuncFlag>\n\t\t\t\t\t\t\t</xml>"; if (!empty($keyword)) { $msgType = "text"; $contentStr = "Welcome to wechat world!"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; } else { echo "Input something..."; } } else { echo ""; exit; } }
public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)) { /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml>\n\t\t\t\t\t\t\t<ToUserName><![CDATA[%s]]></ToUserName>\n\t\t\t\t\t\t\t<FromUserName><![CDATA[%s]]></FromUserName>\n\t\t\t\t\t\t\t<CreateTime>%s</CreateTime>\n\t\t\t\t\t\t\t<MsgType><![CDATA[%s]]></MsgType>\n\t\t\t\t\t\t\t<Content><![CDATA[%s]]></Content>\n\t\t\t\t\t\t\t<FuncFlag>0</FuncFlag>\n\t\t\t\t\t\t\t</xml>"; if (!empty($keyword)) { $msgType = "text"; //$contentStr = "Welcome to wechat world!您的openID:$fromUsername"; $contentStr = "欢迎关注优派健康。\n"; $contentStr .= "<a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxca232ac09f1798ef&redirect_uri=http://api.didijiankang.cn/weixin/index.php/Home/Index/bindingAccountForm&response_type=code&scope=snsapi_base&state=123#wechat_redirect'>注册-绑定优派账号</a>。\n"; $contentStr .= "已绑定账号-<a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxca232ac09f1798ef&redirect_uri=http://api.didijiankang.cn/weixin/index.php/Home/Index/displayMyConcern&response_type=code&scope=snsapi_base&state=123#wechat_redirect'>我的关注</a>。"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; } else { echo "Input something..."; } } else { echo ""; exit; } }
/** * {@inheritdoc} */ protected function stringMatches($other) { $internalErrors = libxml_use_internal_errors(true); $disableEntities = libxml_disable_entity_loader(true); libxml_clear_errors(); $dom = new \DOMDocument(); $dom->preserveWhiteSpace = false; $dom->validateOnParse = true; if (!@$dom->loadXML($other, LIBXML_NONET | (defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0))) { libxml_disable_entity_loader($disableEntities); $this->setXMLConstraintErrors(); libxml_clear_errors(); libxml_use_internal_errors($internalErrors); return false; } $dom->normalizeDocument(); libxml_disable_entity_loader($disableEntities); libxml_clear_errors(); if (false === ($result = @$dom->schemaValidateSource($this->XSD))) { $this->setXMLConstraintErrors(); } libxml_clear_errors(); libxml_use_internal_errors($internalErrors); return $result; }
private function parseFull($xml, $encoding = null) { $dom = new \DomDocument(); if ($encoding) { $xml = '<?xml encoding="' . $encoding . '">' . $xml; } libxml_disable_entity_loader(); // prevents XXE attacks $prevErrorSetting = libxml_use_internal_errors(true); if ($dom->loadXML($xml)) { if ($encoding) { foreach ($dom->childNodes as $item) { if ($item->nodeType == XML_PI_NODE) { $dom->removeChild($item); break; } } $dom->encoding = $encoding; } libxml_use_internal_errors($prevErrorSetting); return new Proxy(simplexml_import_dom($dom), $this); } $errors = libxml_get_errors(); libxml_clear_errors(); libxml_use_internal_errors($prevErrorSetting); $message = 'Incorrect xml passed.'; foreach ($errors as $error) { $message .= '\\nline: ' . $error->line . '; column: ' . $error->column . '; ' . $error->message; } throw new \arc\UnknownError($message, \arc\exceptions::ILLEGAL_ARGUMENT); }
/** * @param FeedTypeInterface $type * @param OutputInterface $output * * @return int */ protected function validate(FeedTypeInterface $type, OutputInterface $output) { $file = $this->exporter->getFeedFilename($type); if (!file_exists($file)) { throw new FileNotFoundException(sprintf('<error>Feed "%s" has not yet been exported</error>', $type->getName())); } $options = LIBXML_NOENT | LIBXML_COMPACT | LIBXML_PARSEHUGE | LIBXML_NOERROR | LIBXML_NOWARNING; $this->reader = new \XMLReader($options); $this->reader->open($file); $this->reader->setParserProperty(\XMLReader::SUBST_ENTITIES, true); // foreach ($type->getNamespaces() as $name => $location) { // $this->reader->setSchema($location); // } libxml_clear_errors(); libxml_use_internal_errors(true); libxml_disable_entity_loader(true); $progress = new ProgressBar($output); $progress->start(); // go through the whole thing while ($this->reader->read()) { if ($this->reader->nodeType === \XMLReader::ELEMENT && $this->reader->name === $type->getItemNode()) { $progress->advance(); $this->currentItem = $this->reader->readOuterXml(); } if ($error = libxml_get_last_error()) { throw new \RuntimeException(sprintf('[%s %s] %s (in %s - line %d, column %d)', LIBXML_ERR_WARNING === $error->level ? 'WARNING' : 'ERROR', $error->code, trim($error->message), $error->file ? $error->file : 'n/a', $error->line, $error->column)); } } $progress->finish(); }
public function responseMsg($conn) { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)) { /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $msgType = $postObj->MsgType; switch ($msgType) { case "text": $this->textHandler($postObj, $conn); exit; case "image": $this->imageHandler($postObj, $conn); exit; case "voice": $this->voiceHandler($postObj, $conn); exit; case "shortvideo": $this->shortvideoHandler($postObj, $conn); exit; default: echo ""; exit; } } else { echo ""; exit; } }
/** * Create a PHP array from the XML file * * @param String $xmlFile The XML file or a string containing xml to parse * * @return Array * * @throws \Propel\Common\Config\Exception\XmlParseException if parse errors occur */ public static function convert($xmlToParse) { if (!is_string($xmlToParse)) { throw new InvalidArgumentException("XmlToArrayConverter::convert method expects an xml file to parse, or a string containing valid xml"); } if (file_exists($xmlToParse)) { $xmlToParse = file_get_contents($xmlToParse); } //Empty xml file returns empty array if ('' === $xmlToParse) { return array(); } if ($xmlToParse[0] !== '<') { throw new InvalidArgumentException('Invalid xml content'); } $currentEntityLoader = libxml_disable_entity_loader(true); $currentInternalErrors = libxml_use_internal_errors(true); $xml = simplexml_load_string($xmlToParse); $errors = libxml_get_errors(); libxml_clear_errors(); libxml_use_internal_errors($currentInternalErrors); libxml_disable_entity_loader($currentEntityLoader); if (count($errors) > 0) { throw new XmlParseException($errors); } $conf = self::simpleXmlToArray($xml); return $conf; }
/** * Convert string with xml data to php array. * * @throws Exception * * @param string $string * * @return array */ public function read($string) { libxml_use_internal_errors(true); libxml_disable_entity_loader(true); $result = simplexml_load_string($string, null, LIBXML_IMPORT_FLAGS); if (!$result) { $errors = libxml_get_errors(); libxml_clear_errors(); foreach ($errors as $error) { $text = ''; switch ($error->level) { case LIBXML_ERR_WARNING: $text .= _s('XML file contains warning %1$s:', $error->code); break; case LIBXML_ERR_ERROR: $text .= _s('XML file contains error %1$s:', $error->code); break; case LIBXML_ERR_FATAL: $text .= _s('XML file contains fatal error %1$s:', $error->code); break; } $text .= trim($error->message) . ' [ Line: ' . $error->line . ' | Column: ' . $error->column . ' ]'; throw new Exception($text); } } $xml = new XMLReader(); $xml->xml($string); $array = $this->xmlToArray($xml); $xml->close(); return $array; }
public function __construct($fileUri, $fileName, $disableExternalEntities = true) { libxml_disable_entity_loader($disableExternalEntities); $this->fileName = $fileName; $this->wordUri = $fileUri; Node::$counter = -1; }
/** * {@inheritdoc} */ public function readBody(HttpRequest $request, \ReflectionClass $type) : \Generator { $input = (yield $request->getBody()->getContents()); $xml = new \DOMDocument(); $xml->formatOutput = false; \libxml_clear_errors(); $errorHandling = \libxml_use_internal_errors(true); $entities = \libxml_disable_entity_loader(true); try { $success = @$xml->loadXML($input, \LIBXML_NONET | \LIBXML_NOENT); $errors = \libxml_get_errors(); } catch (\Throwable $e) { if (!empty($errors) && $this->logger) { $this->logErrors($errors); } throw new StatusException(Http::BAD_REQUEST, 'Invalid XML input', [], $e); } finally { \libxml_use_internal_errors($errorHandling); \libxml_disable_entity_loader($entities); } if (!empty($errors) || empty($success) || $xml === NULL || !$xml instanceof \DOMDocument) { if (!empty($errors) && $this->logger) { $this->logErrors($errors); } throw new StatusException(Http::BAD_REQUEST, 'Invalid XML input'); } return $xml; }
/** * This function attempts to validate an XML string against the specified schema. * * It will parse the string into a DOM document and validate this document against the schema. * * @param string $xml The XML string or document which should be validated. * @param string $schema The schema filename which should be used. * @param boolean $debug To disable/enable the debug mode * * @return string | DOMDocument $dom string that explains the problem or the DOMDocument */ public static function validateXML($xml, $schema, $debug = false) { assert('is_string($xml) || $xml instanceof DOMDocument'); assert('is_string($schema)'); libxml_clear_errors(); libxml_use_internal_errors(true); if ($xml instanceof DOMDocument) { $dom = $xml; } else { $dom = new DOMDocument(); $dom = self::loadXML($dom, $xml); if (!$dom) { return 'unloaded_xml'; } } $schemaFile = dirname(__FILE__) . '/schemas/' . $schema; $oldEntityLoader = libxml_disable_entity_loader(false); $res = $dom->schemaValidate($schemaFile); libxml_disable_entity_loader($oldEntityLoader); if (!$res) { $xmlErrors = libxml_get_errors(); syslog(LOG_INFO, 'Error validating the metadata: ' . var_export($xmlErrors, true)); if ($debug) { foreach ($xmlErrors as $error) { echo $error->message . "\n"; } } return 'invalid_xml'; } return $dom; }
/** * Boot up the Spotweb system * * @return array (Services_Settings_Container|Dao_Factory_Base|SpotReq)[] */ public function boot() { SpotTiming::start('bootstrap'); $daoFactory = $this->getDaoFactory(); $settings = $this->getSettings($daoFactory, true); $spotReq = $this->getSpotReq($settings); /* * Set the cache path */ if ($settings->exists('cache_path')) { $daoFactory->setCachePath($settings->get('cache_path')); } # if /* * Run the validation of the most basic systems * in Spotweb */ $this->validate(new Services_Settings_Base($settings, $daoFactory->getBlackWhiteListDao())); /* * Disable the timing part as soon as possible because it * gobbles memory */ if (!$settings->get('enable_timing')) { SpotTiming::disable(); } # if /* * Disable XML entity loader as this might be an * security issue. */ libxml_disable_entity_loader(true); SpotTiming::stop('bootstrap'); return array($settings, $daoFactory, $spotReq); }
/** * Get a DomDocument instance or return false * * @static * @access public * @param string $input XML content * @return mixed */ public static function getDomDocument($input) { if (substr(php_sapi_name(), 0, 3) === 'fpm') { // If running with PHP-FPM and an entity is detected we refuse to parse the feed // @see https://bugs.php.net/bug.php?id=64938 if (strpos($input, '<!ENTITY') !== false) { return false; } } else { libxml_disable_entity_loader(true); } libxml_use_internal_errors(true); $dom = new DomDocument(); $dom->loadXml($input, LIBXML_NONET); // The document is empty, there is probably some parsing errors if ($dom->childNodes->length === 0) { return false; } // Scan for potential XEE attacks using ENTITY foreach ($dom->childNodes as $child) { if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { if ($child->entities->length > 0) { return false; } } } return $dom; }
public function actionPublic($appid, $echostr = null, $signature = null, $timestamp = null, $nonce = null, $encrypt_type = null, $msg_signature = null) { $this->module->manager->setApp($appid); //验证消息 if (!$this->module->checkSignature($signature, $timestamp, $nonce)) { throw new NotFoundHttpException(\Yii::t('common', 'Page not found.')); } //返回服务器地址设置随机字符串 if ($echostr) { return $echostr; } //过滤非消息请求 if (!($postStr = file_get_contents('php://input'))) { throw new NotFoundHttpException(\Yii::t('common', 'Page not found.')); } //获取数据 libxml_disable_entity_loader(true); $postObj = (array) simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); //确定是否开启安全模式 $safeMode = $encrypt_type && $msg_signature; //安全模式下验证并解密消息 if ($safeMode && (!isset($postObj['Encrypt']) || !($postObj = $this->module->decryptMessage($msg_signature, $timestamp, $nonce, $postObj['Encrypt'])))) { throw new NotFoundHttpException(\Yii::t('common', 'Page not found.')); } //处理数据并获取回复结果 $response = $this->module->handleMessage($postObj); //加密回复消息 if ($safeMode && $response) { $response = $this->module->encryptMessage($response, $timestamp, $nonce); } //设置xml格式 \Yii::$app->response->formatters[Response::FORMAT_XML] = 'yii\\wechat\\components\\XmlResponseFormatter'; \Yii::$app->response->format = Response::FORMAT_XML; return $response; }
public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)) { /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $MsgType = trim($postObj->MsgType); switch ($MsgType) { case "text": $resultStr = $this->responseText($postObj); break; case "image": $resultStr = $this->handleImage($postObj); break; case "voice": $resultStr = $this->handleVoice($postObj); break; default: $resultStr = "Unknow message type: " . $MsgType; break; } echo $resultStr; } else { echo ""; exit; } }
public function __construct($db = null) { libxml_disable_entity_loader(false); if ($db !== null) { $this->cache = new cache($db, "xml"); } }
/** * Extract metadata from document * * @param \ZipArchive $package ZipArchive AbstractOpenXML package * @return array Key-value pairs containing document meta data */ protected function extractMetaData(\ZipArchive $package) { // Data holders $coreProperties = array(); // Prevent php from loading remote resources $loadEntities = libxml_disable_entity_loader(true); // Read relations and search for core properties $relations = simplexml_load_string($package->getFromName("_rels/.rels")); // Restore entity loader state libxml_disable_entity_loader($loadEntities); foreach ($relations->Relationship as $rel) { if ($rel["Type"] == self::SCHEMA_COREPROPERTIES) { // Found core properties! Read in contents... $contents = simplexml_load_string($package->getFromName(dirname($rel["Target"]) . "/" . basename($rel["Target"]))); foreach ($contents->children(self::SCHEMA_DUBLINCORE) as $child) { $coreProperties[$child->getName()] = (string) $child; } foreach ($contents->children(self::SCHEMA_COREPROPERTIES) as $child) { $coreProperties[$child->getName()] = (string) $child; } foreach ($contents->children(self::SCHEMA_DUBLINCORETERMS) as $child) { $coreProperties[$child->getName()] = (string) $child; } } } return $coreProperties; }
/** * When called non-statically (as an object method) with malicious data, no Exception is thrown, but the object is emptied of all DOM nodes. * * @param string $source The string containing the XML. * @param int $options Bitwise OR of the libxml option constants. http://us3.php.net/manual/en/libxml.constants.php * * @return bool|DOMDocument true on success, false on failure. If called statically (E_STRICT error), returns DOMDocument on success. */ public function loadXML($source, $options = 0) { if ('' === $source) { // "If an empty string is passed as the source, a warning will be generated." // "This warning is not generated by libxml and cannot be handled using libxml's error handling functions." trigger_error('WC_Safe_DOMDocument::loadXML(): Empty string supplied as input', E_USER_WARNING); return false; } $old = null; if (function_exists('libxml_disable_entity_loader')) { $old = libxml_disable_entity_loader(true); } $return = parent::loadXML($source, $options); if (!is_null($old)) { libxml_disable_entity_loader($old); } if (!$return) { return $return; } // "This method *may* be called statically, but will issue an E_STRICT error." $is_this = is_object($this); $object = $is_this ? $this : $return; if (isset($object->doctype)) { if ($is_this) { // Get rid of the dangerous input by removing *all* nodes while ($this->firstChild) { $this->removeChild($this->firstChild); } } trigger_error('WC_Safe_DOMDocument::loadXML(): Unsafe DOCTYPE Detected', E_USER_WARNING); return false; } return $return; }
/** * Method parses a mirror.xml file. * * @param string $file GZIP stream resource * @return void * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException in case of XML parser errors */ public function parseXml($file) { $this->createParser(); if (!is_resource($this->objXml)) { throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException('Unable to create XML parser.', 1342641009); } // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept $previousValueOfEntityLoader = libxml_disable_entity_loader(true); // keep original character case of XML document xml_parser_set_option($this->objXml, XML_OPTION_CASE_FOLDING, false); xml_parser_set_option($this->objXml, XML_OPTION_SKIP_WHITE, false); xml_parser_set_option($this->objXml, XML_OPTION_TARGET_ENCODING, 'utf-8'); xml_set_element_handler($this->objXml, 'startElement', 'endElement'); xml_set_character_data_handler($this->objXml, 'characterData'); if (!($fp = fopen($file, 'r'))) { throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException(sprintf('Unable to open file resource %s.', $file), 1342641010); } while ($data = fread($fp, 4096)) { if (!xml_parse($this->objXml, $data, feof($fp))) { throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException(sprintf('XML error %s in line %u of file resource %s.', xml_error_string(xml_get_error_code($this->objXml)), xml_get_current_line_number($this->objXml), $file), 1342641011); } } libxml_disable_entity_loader($previousValueOfEntityLoader); xml_parser_free($this->objXml); }
/** * @return DOMDocument DOM to manipulate */ public function getDoc() { if (!$this->doc) { // DOMDocument::loadHTML apparently isn't very good with encodings, so // convert input to ASCII by encoding everything above 128 as entities. if (function_exists('mb_convert_encoding')) { $html = mb_convert_encoding($this->html, 'HTML-ENTITIES', 'UTF-8'); } else { $html = preg_replace_callback('/[\\x{80}-\\x{10ffff}]/u', function ($m) { return '&#' . UtfNormal\Utils::utf8ToCodepoint($m[0]) . ';'; }, $this->html); } // Workaround for bug that caused spaces before references // to disappear during processing: https://phabricator.wikimedia.org/T55086 // TODO: Please replace with a better fix if one can be found. $html = str_replace(' <', ' <', $html); libxml_use_internal_errors(true); $loader = libxml_disable_entity_loader(); $this->doc = new DOMDocument(); $this->doc->strictErrorChecking = false; $this->doc->loadHTML($html); libxml_disable_entity_loader($loader); libxml_use_internal_errors(false); $this->doc->encoding = 'UTF-8'; } return $this->doc; }
/** * {@inheritdoc} */ public function decode($data, $format) { $internalErrors = libxml_use_internal_errors(true); $disableEntities = libxml_disable_entity_loader(true); libxml_clear_errors(); $dom = new \DOMDocument(); $dom->loadXML($data, LIBXML_NONET); libxml_use_internal_errors($internalErrors); libxml_disable_entity_loader($disableEntities); foreach ($dom->childNodes as $child) { if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { throw new UnexpectedValueException('Document types are not allowed.'); } } $xml = simplexml_import_dom($dom); if ($error = libxml_get_last_error()) { throw new UnexpectedValueException($error->message); } if (!$xml->count()) { if (!$xml->attributes()) { return (string) $xml; } $data = array(); foreach ($xml->attributes() as $attrkey => $attr) { $data['@' . $attrkey] = (string) $attr; } $data['#'] = (string) $xml; return $data; } return $this->parseXml($xml); }
/** * 根据消息的类型,回复不同内容 * @param Request $request * @return null */ public function switchRespMsg(Request $request) { //获取POST数据包 $postStr = $request->getContent(); Log::info($postStr); if (!empty($postStr)) { libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $msgType = $postObj->MsgType; $content = trim($postObj->Content); if ($msgType == "text") { return ResponseMsgService::responseTextMsg($fromUsername, $toUsername, $content); } if ($msgType == "event") { $event = $postObj->Event; Log::info("====event===" . $event); if ($event == "subscribe") { $respStr = "您好,我是郭世杰,欢迎关注我的微信个人公众号"; return ResponseMsgService::responseTextMsg($fromUsername, $toUsername, $respStr); } if ($event == "CLICK") { $eventKey = $postObj->EventKey; return $this->responseMenuMsg($fromUsername, $toUsername, $eventKey); } } return null; } else { Log::info("Post Xml data is null"); return null; } }
public function responseMsg() { //获取微信发送过来的post请求数据 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; if (!empty($postStr)) { libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $msgtype = $postObj->MsgType; $time = time(); $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>"; $data = ''; //返回给用户的数据 //如果推送类型是事件 if (strtolower($postObj->MsgType) == "event") { //关注公众号事件 if (strtolower($postObj->Event == "subscribe")) { $data .= "欢迎来到极致玩家!"; } //用户发消息给公众号 } elseif (strtolower($postObj->MsgType) == "text") { //获取文本 $content = trim($postObj->Content); $data .= "留言成功!"; } //格式化返回给微信的数据 echo sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $data); } }
/** * @param string $xml * * @return \DOMDocument */ public static function fromString($xml) { if (!is_string($xml) || trim($xml) === '') { throw InvalidArgumentException::invalidType('non-empty string', $xml); } $entityLoader = libxml_disable_entity_loader(true); $internalErrors = libxml_use_internal_errors(true); libxml_clear_errors(); $domDocument = self::create(); $options = LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_NONET; if (defined(LIBXML_COMPACT)) { $options |= LIBXML_COMPACT; } $loaded = $domDocument->loadXML($xml, $options); libxml_use_internal_errors($internalErrors); libxml_disable_entity_loader($entityLoader); if (!$loaded) { $error = libxml_get_last_error(); libxml_clear_errors(); throw new UnparseableXmlException($error); } libxml_clear_errors(); foreach ($domDocument->childNodes as $child) { if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { throw new RuntimeException('Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body'); } } return $domDocument; }
/** * @param string $file * @return \Doctrine\DBAL\Schema\Schema * @throws \DomainException */ public function loadSchemaFromFile($file) { $schema = new \Doctrine\DBAL\Schema\Schema(); $loadEntities = libxml_disable_entity_loader(false); $xml = simplexml_load_file($file); libxml_disable_entity_loader($loadEntities); foreach ($xml->children() as $child) { /** * @var \SimpleXMLElement $child */ switch ($child->getName()) { case 'name': case 'create': case 'overwrite': case 'charset': break; case 'table': $this->loadTable($schema, $child); break; default: throw new \DomainException('Unknown element: ' . $child->getName()); } } return $schema; }
public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)) { /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml>\n\t\t\t\t\t\t\t<ToUserName><![CDATA[%s]]></ToUserName>\n\t\t\t\t\t\t\t<FromUserName><![CDATA[%s]]></FromUserName>\n\t\t\t\t\t\t\t<CreateTime>%s</CreateTime>\n\t\t\t\t\t\t\t<MsgType><![CDATA[%s]]></MsgType>\n\t\t\t\t\t\t\t<Content><![CDATA[%s]]></Content>\n\t\t\t\t\t\t\t<FuncFlag>0</FuncFlag>\n\t\t\t\t\t\t\t</xml>"; if (!empty($keyword)) { if ($keyword == 'openid') { echo 'http://www.u-says.com/wechat/getcodeurl.php'; } else { $msgType = "text"; //start to process message $contentStr = file_get_contents("http://www.u-says.com/index.php?route=wechat/msghandler&from=" . urlencode($fromUsername) . "&msg=" . urlencode($keyword)); //$contentStr="hello"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; } } else { echo "Input something..."; } } else { echo ""; exit; } }
/** * @param Request $request * @param IdentityProvider $identityProvider * @param ServiceProvider $serviceProvider * @return Assertion * @throws AuthnFailedSamlResponseException * @throws NoAuthnContextSamlResponseException * @throws PreconditionNotMetException */ public function processResponse(Request $request, IdentityProvider $identityProvider, ServiceProvider $serviceProvider) { $response = $request->request->get('SAMLResponse'); if (!$response) { throw new BadRequestHttpException('Response must include a SAMLResponse, none found'); } $response = base64_decode($response); $previous = libxml_disable_entity_loader(true); $asXml = SAML2_DOMDocumentFactory::fromString($response); libxml_disable_entity_loader($previous); try { $assertions = $this->responseProcessor->process($serviceProvider, $identityProvider, new SAML2_Configuration_Destination($serviceProvider->getAssertionConsumerUrl()), new SAML2_Response($asXml->documentElement)); } catch (PreconditionNotMetException $e) { $message = $e->getMessage(); $noAuthnContext = substr(SAML2_Const::STATUS_NO_AUTHN_CONTEXT, strlen(SAML2_Const::STATUS_PREFIX)); if (false !== strpos($message, $noAuthnContext)) { throw new NoAuthnContextSamlResponseException($message, 0, $e); } $authnFailed = substr(SAML2_Const::STATUS_AUTHN_FAILED, strlen(SAML2_Const::STATUS_PREFIX)); if (false !== strpos($message, $authnFailed)) { throw new AuthnFailedSamlResponseException($message, 0, $e); } throw $e; } return $assertions->getOnlyElement(); }
/** * Scan the input for XXE attacks. * * @param string $input * Unsafe input * @param Closure $callback * Callback called to build the dom. * Must be an instance of DomDocument and receives the input as argument * * @return bool|DomDocument False if an XXE attack was discovered, * otherwise the return of the callback */ private static function scanInput($input, Closure $callback) { $isRunningFpm = substr(php_sapi_name(), 0, 3) === 'fpm'; if ($isRunningFpm) { // If running with PHP-FPM and an entity is detected we refuse to parse the feed // @see https://bugs.php.net/bug.php?id=64938 if (strpos($input, '<!ENTITY') !== false) { return false; } } else { $entityLoaderDisabled = libxml_disable_entity_loader(true); } libxml_use_internal_errors(true); $dom = $callback($input); // Scan for potential XEE attacks using ENTITY foreach ($dom->childNodes as $child) { if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) { if ($child->entities->length > 0) { return false; } } } if ($isRunningFpm === false) { libxml_disable_entity_loader($entityLoaderDisabled); } return $dom; }
/** * Use this sample file to test attack (user contribution) * <?xml version='1.0' encoding='UTF-8'?><!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> * <platforms> * <platform> * <name>&xxe;</name> * </platform> * </platforms> * */ function simplexml_load_file_wrapper($filename) { // http://websec.io/2012/08/27/Preventing-XXE-in-PHP.html libxml_disable_entity_loader(true); $zebra = file_get_contents($filename); $xml = @simplexml_load_string($zebra); return $xml; }
/** * 捕获微信消息 * * @return string */ function getData() { $postStr = file_get_contents('php://input'); file_put_contents('./wechat.txt', $postStr); libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); return json_decode(json_encode($postObj), false); }