<?php

//加载第三方用于解析html的类
require '/lib/simple_html_dom.php';

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class MY_Output extends CI_Output {
    // --------------------------------------------------------------------

    /**
     * Write a Cache File
     *
     * @access	public
     * @param 	string
     * @return	void
     */
    function _write_cache($output) {
        $cache_path = 'd:/Dropbox/wwwcache/asiahighlights.com';
        $optimize_js_path = 'd:/Dropbox/wwwcache/asiahighlights.com/js';

        if (!is_dir($cache_path) OR ! is_really_writable($cache_path)) {
            log_message('error', "Unable to write cache file: " . $cache_path);
            return;
        }

        ///////改成按照URL保存缓存
        //优先使用提交过来的static_html_url做文件名，这是主动生成静态文件用的参数
        if (empty($_GET['static_html_url'])) {
            return FALSE;
        }
        $cache_path = $cache_path . $_GET['static_html_url'];
        if (mb_substr($cache_path, -1, 1) == '/') {
            $cache_path.='index.htm';
        }

        $this->create_folder_by_path(dirname($cache_path));

        //如果文件存在，先判断是否为缓存文件，防止覆盖原始程序文件
        if (@file_exists($cache_path) && filesize($cache_path) > 0) {
            if (!$fp_read = @fopen($cache_path, FOPEN_READ)) {
                return FALSE;
            }

            flock($fp_read, LOCK_SH);

            $cache = fread($fp_read, filesize($cache_path));

            flock($fp_read, LOCK_UN);
            fclose($fp_read);
            if (strpos($cache, '<!-- Generated by ') === false) {
                log_message('error', "is not cache file." . $cache_path);
                return FALSE;
            }
        }

        ///////

        if (!$fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE)) {
            log_message('error', "Unable to write cache file: " . $cache_path);
            return;
        }

        //精简html和css代码
        if (!empty($_GET['static_html_optimize'])) {//设置优化开关，暂时手动优化
            $optimize_html = $_GET['static_html_optimize'];
            if ($optimize_html === 'comeon') {
                $clean_html = GET_HTTP('http://cht.mycht.cn/info.php/apps/htmlcompressor/index/optimize', 'websitehost=' . urlencode('https://data.asiahighlights.com') . '&htmlsource=' . urlencode($output), 'POST');
                //$clean_html = GET_HTTP('http://202.103.68.110:8001/info.php/apps/htmlcompressor/index/optimize', 'websitehost=' . urlencode('https://data.asiahighlights.com') . '&htmlsource=' . urlencode($output), 'POST');
                if (!empty($clean_html)) {
                    $clean_html_object = json_decode($clean_html);
                    if (!empty($clean_html_object) && $clean_html_object->result == 'ok') {
                        $output = $clean_html_object->data->html_object;
                        $output_js = $clean_html_object->data->js_content;
                        $output_js_name = '/' . md5($cache_path) . '.js';
                        file_put_contents($optimize_js_path . $output_js_name, $output_js);
                        $time_mark=  time();//添加时间戳，用来更新CDN
                        $output = str_replace('##DEFERSCRIPTDEFER##', 'https://data.asiahighlights.com/optimizejs' . $output_js_name.'?'.$time_mark, $output);
                    }
                }
            }
        }
        //解析html，生成不同版本的静态文件

        $html_object = str_get_html($output);
        if (!empty($html_object)) {

            //替换图片地址，用CDN分发
            foreach ($html_object->find('img') as $image) {
                if (strpos($image->src, 'https://data.asiahighlights.com/') === false) {//当查找的字符串在开始位置则返回0，所以一定要写===false
                    if (strpos($image->src, '/pic/') !== false  || strpos($image->src, '/image/') !== false) {
                        $image->src = 'https://data.asiahighlights.com' . $image->src;
                    } 
                }
                if(empty($image->loader) || $image->loader!=="nolazy") {//如果没有禁止懒加载的标识符，则给图片添加懒加载。一般首页logo和banner图片不需要懒加载
                    $image->originalsrc = $image->src;
                    $image->loader = "lazy";
                    $image->src = "https://data.asiahighlights.com/image/grey.gif";
                }
            }
            //保存PC端代码
            $output = $html_object->save();

            //生成移动版本
            foreach ($html_object->find('.hidden-xs') as $hidden_item) {
                $hidden_item->outertext = '';
            }

            //生成移动端用小图
            foreach ($html_object->find('img') as $image) {
                if(substr($image->originalsrc,-4)=='.jpg'){//只有jpg可以处理
                    if (strpos($image->originalsrc, 'https://data.asiahighlights.com/') !== false) {//当查找的字符串在开始位置则返回0，所以一定要写===false
                        $source_image = str_replace('https://data.asiahighlights.com', '', $image->originalsrc); //原始图片URL
                        $image->originalsrc = 'https://data.asiahighlights.com/mobile' . $source_image;
                    }
                }
            }
            $html_object->save($cache_path . '.mobile.htm');
        }

        ////// 
		
		
		////// 生成AMP版本
        ///
		//用移动端版本生成
		/*
		    1.头部添加amp表示
            2.删除全部js引用和内链代码
            3.删除全部css引用，内联css放入<style amp-custom>
            4.添加AMP的js和meta标记
            5.图片全部替换成amp-img，设置宽高，设置layout="responsive"
            6.去掉所有元素中的style
            7.去掉样式表中的!important
            8.替换导航为AMP版本
            9.添加社媒分享和GA代码
            10.添加回到顶部插件
		 */
        if (!empty($_GET['amp_optimize'])) {//生成AMP版本

            foreach ($html_object->find('html') as $html) {
                $html->amp = true;
            }
            foreach ($html_object->find('script') as $script) {
                $script->outertext = '';
            }
            foreach ($html_object->find('link') as $link_css) {
                if ($link_css->rel == 'stylesheet' && !empty($link_css->href)) {
                    $link_css->outertext = '';
                }
            }
            $style_content = '';
            foreach ($html_object->find('style') as $style) {
                $style_content .= $style->innertext;
                $style->outertext = '';
            }
            //判断是否有viewport标识
            $has_viewport = false;
            foreach ($html_object->find('meta') as $meta) {
                if ($meta->name == 'viewport') {
                    $has_viewport = true;
                    $meta->outertext = '<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">';
                }
            }

            $style_content = str_replace('!important', '', $style_content);
            $amp_header = '';
            //viewport标识只能有一个
            if ($has_viewport == false) {
                $amp_header .= '<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">';
            }
            $amp_header .= '<script async="" src="https://cdn.ampproject.org/v0.js"></script>';
            $amp_header .= '<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>';
            $amp_header .= '<script custom-element="amp-sidebar" src="https://cdn.ampproject.org/v0/amp-sidebar-0.1.js" async></script>';
            $amp_header .= '<script async custom-element="amp-accordion" src="https://cdn.ampproject.org/v0/amp-accordion-0.1.js"></script>';
            $amp_header .= '<script async custom-element="amp-position-observer" src="https://cdn.ampproject.org/v0/amp-position-observer-0.1.js"></script>';
            $amp_header .= '<script async custom-element="amp-animation" src="https://cdn.ampproject.org/v0/amp-animation-0.1.js"></script>';

            $amp_header .= '<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript> ';
			
			//添加导航和底部的CSS
			$amp_navbar_footer_css=<<<EOT
			
	html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:0;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}button,[type="button"],[type="reset"],[type="submit"]{-webkit-appearance:button}button::-moz-focus-inner,[type="button"]::-moz-focus-inner,[type="reset"]::-moz-focus-inner,[type="submit"]::-moz-focus-inner{border-style:none;padding:0}button:-moz-focusring,[type="button"]:-moz-focusring,[type="reset"]:-moz-focusring,[type="submit"]:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type="checkbox"],[type="radio"]{box-sizing:border-box;padding:0}[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button{height:auto}[type="search"]{-webkit-appearance:textfield;outline-offset:-2px}[type="search"]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}		
			
/*YCCCCCCCC*/a{background-color:transparent;-webkit-text-decoration-skip:objects;color:#545454}a:active,a:hover{outline-width:0}svg:not(:root){overflow:hidden}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}.text-decoration-none{text-decoration:none}.center{text-align:center}.nowrap{white-space:nowrap}.list-reset{list-style:none;padding-left:0}.block{display:block}.inline-block{display:inline-block}.m0{margin:0}.my0{margin-top:0;margin-bottom:0}.mb1{margin-bottom:.5rem}.mt2{margin-top:1rem}.mr2{margin-right:1rem}.mb4{margin-bottom:2rem}.mx-auto{margin-right:auto}.mx-auto{margin-left:auto}.p0{padding:0}.pr0{padding-right:0}.pt2{padding-top:1rem}.pr2{padding-right:1rem}.pl2{padding-left:1rem}.pr3{padding-right:1.5rem}.pr4{padding-right:2rem}.flex{display:-webkit-box;display:-ms-flexbox;display:flex}@media(min-width:52.06rem){.md-flex{display:-webkit-box;display:-ms-flexbox;display:flex}}.flex-column{-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column}.items-start{-webkit-box-align:start;-ms-flex-align:start;align-items:flex-start}.items-center{-webkit-box-align:center;-ms-flex-align:center;align-items:center}.justify-start{-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start}.justify-center{-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center}.absolute{position:absolute}.top-0{top:0}.right-0{right:0}.left-0{left:0}*{box-sizing:border-box}.ampstart-label{font-size:1.125rem;color:#4f4f4f;line-height:1.125rem;letter-spacing:.06rem}.ampstart-label{text-transform:uppercase}a,a:active,a:visited{color:inherit}@media(min-width:52.06rem){.md-mb0{margin-bottom:0}}@media(min-width:52.06rem){.md-pt0{padding-top:0}}.ampstart-headerbar{background-color:#fff;color:#000;z-index:999;box-shadow:0 0 5px 2px rgba(0,0,0,.1);position:fixed}.ampstart-nav-item:active,.ampstart-nav-item:focus,.ampstart-nav-item:hover{opacity:1}.ampstart-navbar-trigger:focus{outline:0}.ampstart-nav a,.ampstart-navbar-trigger{cursor:pointer;text-decoration:none}.ampstart-nav .ampstart-label{color:inherit}.ampstart-navbar-trigger{line-height:3.5rem;font-size:2.2rem}.ampstart-sidebar{background-color:#fff;color:#000;min-width:300px;width:300px}.ampstart-sidebar-header{line-height:3.5rem;min-height:3.5rem}.ampstart-sidebar .ampstart-nav-item{margin:0 0 2rem}.ampstart-sidebar .ampstart-navbar-trigger{line-height:inherit}.ampstart-navbar-trigger svg{pointer-events:none}@media(min-width:52.06rem){.md-pt5{padding-top:2.5rem}.md-pb5{padding-bottom:2.5rem}}.commerce-loader,.commerce-loader:after,.commerce-loader:before{border-radius:50%;width:.5rem;height:.5rem;-webkit-animation-fill-mode:both;animation-fill-mode:both;-webkit-animation:a 1.44s infinite ease-in-out;animation:a 1.44s infinite ease-in-out;will-change:contents}.commerce-loader{color:#666;margin:24% auto;-webkit-animation-delay:.16s;animation-delay:.16s}.commerce-loader:after,.commerce-loader:before{content:"";position:absolute;top:0}.commerce-loader:before{left:-1rem;-webkit-animation-delay:0s;animation-delay:0s}.commerce-loader:after{left:1rem;-webkit-animation-delay:.32s;animation-delay:.32s}@-webkit-keyframes a{0%,80%,to{box-shadow:0 1rem 0 -1rem}40%{box-shadow:0 1rem 0 0}}@keyframes a{0%,80%,to{box-shadow:0 1rem 0 -1rem}40%{box-shadow:0 1rem 0 0}}@media(min-width:52.06rem){.ampstart-headerbar+amp-sidebar+*{margin-top:5rem}}.ampstart-headerbar{color:#f88;padding-right:1rem;background-color:#fff;height:3.5rem;box-shadow:none;border-bottom:1px solid #f3f3f3}.ampstart-headerbar .ampstart-navbar-trigger{color:#222;font-size:1.38rem;padding-right:0}.ampstart-navbar-trigger:focus{outline:5px auto -webkit-focus-ring-color}@media(min-width:52.06rem){.ampstart-headerbar{height:5rem;border-bottom-color:#f3f3f3}.ampstart-headerbar .ampstart-navbar-trigger{margin-left:.5rem;top:.5rem}}.ampstart-headerbar-home-link{padding-bottom:0}@media(min-width:52.06rem){.ampstart-headerbar-fixed{top:.5rem}}.ampstart-sidebar{background-color:#fff;width:350px;margin-bottom:1.5rem;text-align:center}@media(min-width:52.06rem){.ampstart-sidebar{width:25%}.ampstart-sidebar-nav{display:inline-block;text-align:left;width:100%}}.ampstart-sidebar-nav-image{width:120px}.ampstart-sidebar-header{position:relative;z-index:1}@media(min-width:52.06rem){.ampstart-sidebar-header{position:absolute;top:0;right:2rem}}.ampstart-sidebar .ampstart-navbar-trigger{margin-top:1rem;font-size:1.5rem;line-height:normal;top:0}@media(min-width:52.06rem){.ampstart-sidebar .ampstart-navbar-trigger{margin-top:.5rem;padding-top:0}}.ampstart-nav{margin-bottom:2rem}.ampstart-nav-item{color:#222;border-bottom:1px solid #999}.ampstart-sidebar .ampstart-nav-item{margin-bottom:1rem;padding-left:30px}.ampstart-nav-link{font-family:Open Sans Condensed,sans-serif;font-size:1.1rem;font-weight:700;line-height:normal;display:inline-block;margin-bottom:1rem;position:relative}.ampstart-nav-link .fa{position:absolute;right:20px;top:3px}.ampstart-dropdown-items{margin-bottom:20px}.ampstart-dropdown-items li{font-size:16px;text-transform:capitalize;line-height:35px;border-bottom:1px solid #f1f1f1;margin-right:30px;padding-left:20px;padding-bottom:5px}.ampstart-dropdown-items li a{color:#666}.ampstart-dropdown-items li:last-child{border-bottom:0}.commerce-footer{background-color:#222}.commerce-footer{color:#fff}.commerce-footer nav{max-width:1280px}@media(min-width:52.06rem){.commerce-footer{text-align:initial}}.tailorM{background:#a31022;padding:3px 3px;color:#fff;text-decoration:none;border-radius:4px;margin-top:3px;display:block;text-align:center;font-family:Arial,Helvetica,sans-serif}.footerLink{display:block;padding:20px 0 0;text-align:center}.footerLink a{margin:0 10px}.copyright{display:block;padding:20px 0;text-align:center}.socialLink{text-align:center}.socialLink a{text-decoration:none}.socialLink .fa{font-size:150%;margin:0 20px;color:#666}@font-face{font-family:FontAwesome;src:url(//data.asiahighlights.com/css/fonts/fontawesome-webfont.eot?v=4.3.0);src:url(//data.asiahighlights.com/css/fonts/fontawesome-webfont.eot?#iefix&v=4.3.0) format('embedded-opentype'),url(//data.asiahighlights.com/css/fonts/fontawesome-webfont.woff2?v=4.3.0) format('woff2'),url(/css/data.asiahighlights.com/css/fonts/fontawesome-webfont.woff?v=4.3.0) format('woff'),url(//data.asiahighlights.com/css/fonts/fontawesome-webfont.ttf?v=4.3.0) format('truetype'),url(//data.asiahighlights.com/css/fonts/fontawesome-webfont.svg?v=4.3.0#fontawesomeregular) format('svg');font-weight:400;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-facebook:before{content:"\f09a"}.fa-twitter:before{content:"\f099"}.fa-instagram:before{content:"\f16d"}.fa-angle-right:before{content:"\f105"}.logo{text-align:center}.amphtml-accordion-header{background:0;border:0}.headerbottom{margin-top:56px}.scrollToTop{opacity:1;height:50px;position:fixed;width:50px;z-index:9999;right:5px;bottom:50px;background:url("https://data.asiahighlights.com/image/to-top.png");cursor:pointer;display:block}#marker{position:absolute;top:100px;width:0;height:0}/*YCCCCCCCC-END*/
			
EOT;
			
            $amp_header .= '<style amp-custom>' . $amp_navbar_footer_css.$style_content . '</style>';
            foreach ($html_object->find('head') as $head) {
                $head->innertext = $head->innertext . $amp_header;
            }

            //替换导航为AMP版本
            $amp_navbar =<<<EOT

<!-- Start Navbar -->
<header class="ampstart-headerbar  flex justify-start items-center top-0 left-0 right-0 pl2 pr4 pt2 md-pt0">
  <div role="button" aria-label="open sidebar" on="tap:header-sidebar.toggle" tabindex="0" class="ampstart-navbar-trigger  pr2 absolute top-0 pr0 mr2 mt2"><svg xmlns="//www.w3.org/2000/svg" width="24" height="24" viewbox="0 0 24 24" class="block">
    <path fill="none" d="M0 0h24v24H0z"></path>
    <path fill="currentColor" d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"></path>
    </svg> </div>
  <a href="/" class="text-decoration-none inline-block mx-auto ampstart-headerbar-home-link mb1 md-mb0 ">
  <amp-img src="https://data.asiahighlights.com/pic/ah-slide-logo.png" width="178" height="45" layout="fixed" class="my0 mx-auto"></amp-img>
  </a>
  <div class="ampstart-headerbar-fixed center m0 p0 flex justify-center nowrap absolute top-0 right-0 pt2 pr3">
    <div class="mr2"> </div>
    <a href="/orders/triprequest.htm" class="tailorM"> CUSTOMIZE </a> </div>
</header>

<!-- Start Sidebar -->
<amp-sidebar id="header-sidebar" class="ampstart-sidebar px3  md-flex flex-column justify-content items-center justify-center" layout="nodisplay">
  <div class="flex justify-start items-center ampstart-sidebar-header">
    <div role="button" aria-label="close sidebar" on="tap:header-sidebar.toggle" tabindex="0" class="ampstart-navbar-trigger items-start">✕</div>
  </div>
  <nav class="ampstart-sidebar-nav ampstart-nav ">
    <ul class="list-reset m0 p0 ampstart-label">
      <li class="logo"> <a href="/" class="text-decoration-none block">
        <amp-img src="https://data.asiahighlights.com/pic/ah-slide-logo.png" width="178" height="45" layout="responsive" class="ampstart-sidebar-nav-image inline-block mb4" alt="Company logo" noloading="">
          <div placeholder="" class="commerce-loader"></div>
        </amp-img>
        </a> </li>
		<li class="ampstart-nav-item m0 p0"><a class="ampstart-nav-link" href="/">HOME</a></li>
      <li class="ampstart-nav-item">

  
<amp-accordion>
  <section>
    <h3 class="ampstart-nav-link amphtml-accordion-header">Plan Your Trip <i class="fa fa-angle-right" aria-hidden="true"></i></h3>
		<ul class="ampstart-dropdown-items list-reset m0 p0 ">
			<li ><a href="/tours/year.htm" >Southeast Asia</a></li>
			<li ><a href="/myanmar/" >Myanmar</a></li>
			<li ><a href="/vietnam/" >Vietnam</a></li>
			<li ><a href="/cambodia/" >Cambodia</a></li>
			<li ><a href="/laos/" >Laos</a></li>
			<li ><a href="/cambodia/angkor-wat-travel-guide.htm" >Angkor Wat</a></li>
			<li ><a href="/southeast-asia/ports-and-shore-excursions.htm" >Arriving by Cruise</a></li>
		</ul>
  </section>
</amp-accordion>
	 
	  
	  </li> 
      <li class="ampstart-nav-item">
<amp-accordion>
  <section>
    <h3 class="ampstart-nav-link amphtml-accordion-header">TOURS <i class="fa fa-angle-right" aria-hidden="true"></i></h3>
		<ul class="ampstart-dropdown-items list-reset m0 p0">
  <li ><a href="/tours/" >Top Asia Tours</a></li>
  <li ><a href="/tours/japan.htm" >Japan Tours</a></li>
  <li ><a href="/tours/myanmar.htm" >Myanmar Tours</a></li>
  <li ><a href="/tours/vietnam.htm" >Vietnam Tours</a></li>
		</ul>
  </section>
</amp-accordion>
	  </li>
      <li class="ampstart-nav-item "><a class="ampstart-nav-link" href="/orders/triprequest.htm">CUSTOMIZE</a></li>
      <li class="ampstart-nav-item "><a class="ampstart-nav-link" href="/about-us.htm">About</a></li>
      <li class="ampstart-nav-item "><a class="ampstart-nav-link" href="/contact-us.htm">Contact</a></li>
    </ul>
	
  </nav>
  <span class="socialLink"><a class="fb fa fa-facebook" title="Follow us on Facebook" rel="nofollow" href="https://www.facebook.com/AsiaHighlights"></a><a class="tw fa fa-twitter" title="Share us on Twitter" rel="nofollow" href="https://twitter.com/Asiahighlights"></a> <a class="tw fa fa-instagram" title="Share us on Instagram" rel="nofollow" href="https://instagram.com/Asiahighlights"></a></span>

</amp-sidebar>
<!-- End Sidebar --> 
<!-- End Navbar -->
<div class="headerbottom" id="top-page"></div>


EOT;

            foreach ($html_object->find('#header') as $headerbar) {
                $headerbar->outertext = $amp_navbar;
            }
			
			//替换底部
$amp_footer=<<<EOT

<footer class="commerce-footer center">
  <nav class="mx-auto md-mb0 md-pt5 md-pb5">
  <div class="footerLink"><a href="/contact-us.htm" >Contact Us</a> | <a href="/about-us.htm" >About Us</a></div>
  <div class="copyright">Copyright © 2018 Asia Highlights</div> 
  </nav>
</footer>
<script type="application/ld+json">{"@context": "http://schema.org","@type": "NewsArticle","@id": "https://www.asiahighlights.com/","mainEntityOfPage": [{
  "@type": "WebPage","@id": "https://google.com/article"}],"headline": "Asia Highlights","author": [{"@type": "Person","name": "WendySong"
  }],"description": "Asia Highlights creates authentic journeys through Asia for the more discerning travelers. ", "image": [{"@type": "ImageObject","url": "https://data.asiahighlights.com/pic/logo-ah.png", "width": "238","height": "117"
  }], "publisher": [{ "@type": "Organization", "name": "Asia Highlights","logo": [{"@type": "ImageObject", "url": "https://data.asiahighlights.com/pic/logo-ah.png", "width": "238", "height": "117"}] }],"datePublished": "2016-03-04 01:51:23.010","dateModified": "2017-12-05 20:13:03.293"
}
</script>
<amp-animation id="showAnim"layout="nodisplay"><script type="application/json">{"duration":"200ms","fill":"both","iterations":"1","direction":"alternate","animations":[{"selector":"#scrollToTopButton","keyframes":[{"opacity":"1","visibility":"visible"}]}]}</script></amp-animation><amp-animation id="hideAnim"layout="nodisplay"><script type="application/json">{"duration":"200ms","fill":"both","iterations":"1","direction":"alternate","animations":[{"selector":"#scrollToTopButton","keyframes":[{"opacity":"0","visibility":"hidden"}]}]}</script></amp-animation><div id="marker"><amp-position-observer on="enter:hideAnim.start; exit:showAnim.start"layout="nodisplay"></amp-position-observer></div><a id="scrollToTopButton"on="tap:top-page.scrollTo(duration=200)"class="scrollToTop"></a>
<amp-analytics type="googleanalytics"><script type="application/json">{"vars": {"account": "UA-75142970-1"},"triggers": { "default pageview": {"on": "visible", "request": "pageview","vars": {"title": "Tailor-made Travel, Asia Tours | Asia Highlights"}}}}</script></amp-analytics>

EOT;

            foreach ($html_object->find('#footer') as $footer) {
                $footer->outertext = $amp_footer;
            }

            //获取图片尺寸，AMP要求必须填写width和height

            //拼接请求的图片url，如 https://data.asiahighlights.com/imagesize.php?photo=/pic/logo-ah.png,/pic/ah-slide-logo.png
            $request_size=array();
            foreach ($html_object->find('img') as $image) {
                $img_src = $image->src;
                if (!empty($image->originalsrc)) {
                    $img_src = $image->originalsrc;
                }
                $request_size[] = str_replace('https://data.asiahighlights.com', '', $img_src);
            }

            //请求图片尺寸
            $image_sizes=array();
            $parse_url='https://data.asiahighlights.com/imagesize.php?photo='.implode(',',$request_size);
            $size_data=GET_HTTP($parse_url);
            if(!empty($size_data)){
                $size_data=json_decode($size_data);
                foreach ($size_data as $item){
                    $item->photo='https://data.asiahighlights.com'.$item->photo;
                    $image_sizes[$item->photo]=$item;
                }
            }

            //获取图片尺寸 end

            foreach ($html_object->find('img') as $image) {
                $img_src = $image->src;
                if (!empty($image->originalsrc)) {
                    $img_src = $image->originalsrc;
                }
                $img_alt = $image->alt;
                $img_class = $image->class;
                $img_size=$image_sizes[$img_src];
                if(!empty($img_size)){
                    $image->outertext = " <amp-img layout='responsive' class='{$img_class}' alt='{$img_alt}' src='{$img_src}' width='{$img_size->width}' height='{$img_size->height}'></amp-img>";
                }
         }

            $amp_source = preg_replace('/style=".*"?/i', '', $html_object);
            $html_object = str_get_html($amp_source);
            $html_object->save($cache_path . '.amp.htm');
        }
		
		////// 生成AMP版本 end

        if (flock($fp, LOCK_EX)) {
            fwrite($fp, $output . '<!-- Generated by ' . $_SERVER['HTTP_HOST'] . ' (' . date('c') . ') -->');
            flock($fp, LOCK_UN);
        } else {
            log_message('error', "Unable to secure a file lock for file at: " . $cache_path);
            return;
        }
        fclose($fp);
        @chmod($cache_path, FILE_WRITE_MODE);

        log_message('debug', "Cache file written: " . $cache_path);
    }

    // --------------------------------------------------------------------

    /*
     * 递归创建文件夹
     */
    function create_folder_by_path($dir, $mode = 0777) {
        if (!is_dir($dir)) {
            return @mkdir($dir, $mode, true);
        }
        return;
    }


    //获取网络图片尺寸
    function GetImageSize($url) {
        $dataBlock=file_get_contents ($url , 0 , NULL , 0 , 168);
        if (!$dataBlock){
            return false;
        }
        // 将读取的图片信息转化为图片路径并获取图片信息,经测试,这里的转化设置 jpeg 对获取png,gif的信息没有影响,无须分别设置
        // 有些图片虽然可以在浏览器查看但实际已被损坏可能无法解析信息
        $size = getimagesize('data://image/jpeg;base64,'. base64_encode($dataBlock));
        if (empty($size)) {
            return false;
        }
        //$result['width'] = $size[0];
       //$result['height'] = $size[1];
        return $size;
    }

}
