获取前端配置JS代码
@Author   Sean       Yan
@DateTime 2018-08-09
@return   [type]     [description]
操作说明：
框架需要安装View组件 并在View的配置文件 新增一条后置代码：wechat::jsSdkCode;
例："rearcode": ["wechat::jsSdkCode"] 注意：切记请勿添加（）添加括号会导致运行出错
967081
public function jsSdkCode($value = '') {
        $debug       = !DEBUG ? false : C("wechat", "debug");
        $jsApiList   = to_json(C("wechat", 'jsApiList'));
        $signPackage = $this->getSignPackage();
        $json        = to_json($signPackage);
        $JS          = <<<CODEJS
<script type="text/javascript">
var signPackage = '{$json}';
wx.config({
    debug: {$debug},
    appId: '{$signPackage["appId"]}',
    timestamp: {$signPackage["timestamp"]},
    nonceStr: '{$signPackage["nonceStr"]}',
    signature: '{$signPackage["signature"]}',
    jsApiList: {$jsApiList}
});
</script>
CODEJS;
        return $JS;
    }
757909
public function showTrace()
    {
        $_trace =   array();
        $included_files = get_included_files();

        // 系统默认显示信息
        if (!empty($this->request->server['SCRIPT_NAME']))
        {
            $_trace['请求脚本'] = $this->request->server['SCRIPT_NAME'];
        }

        $_trace['请求方法'] = $this->swoole->env['mvc']['controller'].'/'.$this->swoole->env['mvc']['view'];
        $_trace['USER_AGENT'] = $this->request->server['HTTP_USER_AGENT'];
        $_trace['HTTP版本'] = $this->request->server['SERVER_PROTOCOL'];
        $_trace['请求时间'] = date('Y-m-d H:i:s', $this->request->server['REQUEST_TIME']);

        if (isset($_SESSION))
        {
            $_trace['SESSION_ID'] = session_id();
        }
        if ($this->swoole->db instanceof \Swoole\Database)
        {
            $_trace['读取数据库'] = $this->swoole->db->read_times . '次';
            $_trace['写入数据库'] = $this->swoole->db->write_times . '次';
        }
        $_trace['加载文件数目'] = count($included_files);
        $_trace['PHP执行占用'] = $this->showTime();
        $_trace = array_merge($this->traceInfo, $_trace);

        // 调用Trace页面模板
        $html = <<<HTMLS
<style type="text/css">
#swoole_trace_content  {
font-family:		Consolas, Courier New, Courier, monospace;
font-size:			14px;
background-color:	#fff;
margin:				40px;
color:				#000;
border:				#999 1px solid;
padding:			20px 20px 12px 20px;
}
</style>
	<div>
		<fieldset style="margin:5px;">
		<div style="overflow:auto;text-align:left;">
HTMLS;
        $html .= "<a href='".Tool::url_merge('_show_request', '1')."'>显示请求参数</a> |
        <a href='".Tool::url_merge('_show_session', '1')."'>显示会话信息</a> |
        <a href='".Tool::url_merge('_show_files', '1')."'>显示加载的PHP文件</a>
        <hr/>";
        foreach ($_trace as $key => $info)
        {
            $html .= $key . ' : ' . $info . BL;
        }
        if (!empty($this->request->get['_show_files']))
        {
            //输出包含的文件
            $html .= '加载的文件：' . BL."<pre style='color: #666'>";
            foreach ($included_files as $file)
            {
                $html .= $file . "\n";
            }
            $html .= "</pre>";
        }
        $html .= "</div></fieldset>";
        $html .= "</div>";

        if (!empty($this->request->get['_show_request']))
        {
            $output = '<fieldset style="margin:5px;"><div style="overflow:auto;text-align:left;">';
            $request = $this->swoole->request;
            $output .= "<h2>HEADER:</h2>".Tool::dump($request->header);
            $output .= "<h2>SERVER:</h2>".Tool::dump($request->server);
            if (!empty($request->files))
            {
                $output .= "<h2>FILE:</h2>".Tool::dump($request->files);
            }
            if (!empty($request->cookie))
            {
                $output .= "<h2>COOKIES:</h2>".Tool::dump($request->cookie);
            }
            if (!empty($request->get))
            {
                $output .= "<h2>GET:</h2>".Tool::dump($this->swoole->request->get);
            }
            if (!empty($request->post))
            {
                $output .= "<h2>POST:</h2>".Tool::dump($request->post);
            }

            $html .= $output."</div></fieldset>";
        }

        if (!empty($this->request->get['_show_session']))
        {
            $output = '<fieldset style="margin:5px;"><div style="overflow:auto;text-align:left;">';
            $this->session->start();
            $output .= "<h2>SESSION:</h2>" . Tool::dump($this->request->session);
            $html .= $output."</div></fieldset>";
        }

        return $html;
    }
942303
function () {

        var htmlFile = this.htmlFile;
        var htmlParser = this.htmlParser;
        var options = this.options;
        var resources = [];

        // 获取外链样式资源
        var cssFiles =  htmlParser.getCssFiles();

        // 获取 style 标签内容资源
        var cssContents =  htmlParser.getCssContents();


        cssFiles.forEach(function (cssFile, index) {

            if (!cssFile) {
                return;
            }

            var line = index + 1;
            var from = 'link:nth-of-type(' + line + ')';

            resources.push(
                new Resource(
                    cssFile,
                    null,
                    utils.options(options, {
                        cache: true,
                        from: from
                    })
                )
            );

        });


        cssContents.forEach(function (content, index) {

            if (!content) {
                return;
            }

            var line = index + 1;
            var from = 'style:nth-of-type(' + line + ')';
            var cssFile = htmlFile + '#' + from;
            resources.push(
                new Resource(
                    cssFile,
                    content,
                    utils.options(options, {
                        cache: false,
                        from: from
                    })
                )
            );
        });



        return Promise.all(resources.map(function (resource) {
            return new CssParser(resource);
        }))

        // 对二维数组扁平化处理
        .then(utils.reduce);
    }
893024
public function createComponentApiService()
    {
        $api = wei()->wechatComponentApi;

        // 如果未设置appSecret,认为是未初始化
        if (!$api->getAppSecret()) {
            // 获取第三方平台的appId(允许指定某个应用使用特定的第三方平台)
            $account = wei()->wechatAccount()->cache()->findOrInit(['applicationId' => $api->getAppId()]);
            $api->setOption([
                'appSecret' => $account['applicationSecret'],
                'verifyTicket' => $account['verifyTicket'],
            ]);
        }

        return $api;
    }
900479
function deleteCodeComments(code) {
    // 另一种思路更简便的办法
    // 将'://'全部替换为特殊字符，删除注释代码后再将其恢复回来
    var tmp1 = ':\/\/';
    var regTmp1 = /:\/\//g;
    var tmp2 = '@:@/@/@';
    var regTmp2 = /@:@\/@\/@/g;
    code = code.replace(regTmp1, tmp2);
    code = code.replace(rComments, '');
    return code.replace(regTmp2, tmp1);
}
80011
function local(backendTplServer) {
    backendTplServer.app.get('/news/local', function(request, response) {
        // 公共的数据模型可以抽取到出来, 作为一个文件 require 进来, 防止多处重复定义数据模型的规则
        var data = Mock.mock({
            'news|10-20': [news]
        });

        // 单独修改其中的某个数据
        data.news[0].getUrls = function() {
            return [
                'http://dummyimage.com/112x74,',
                'http://dummyimage.com/112x74,',
                'http://dummyimage.com/112x74,',
                'http://dummyimage.com/112x74,'
            ]
        };

        response.render('news/local.html', data);
    });
}
1187227
function (_this) {
    var menuLeft;
    var menuTop;

    // 菜单位置和方向
    var position;
    var align;

    // window 窗口的宽度和高度
    var windowHeight = $window.height();
    var windowWidth = $window.width();

    // 配置参数
    var gutter = _this.options.gutter;
    var isCovered = _this.isCovered;
    var isFixed = _this.options.fixed;

    // 动画方向参数
    var transformOriginX;
    var transformOriginY;

    // 菜单的原始宽度和高度
    var menuWidth = _this.$menu.width();
    var menuHeight = _this.$menu.height();

    var $anchor = _this.$anchor;

    // 触发菜单的元素在窗口中的位置
    var anchorTmp = $anchor[0].getBoundingClientRect();
    var anchorTop = anchorTmp.top;
    var anchorLeft = anchorTmp.left;
    var anchorHeight = anchorTmp.height;
    var anchorWidth = anchorTmp.width;
    var anchorBottom = windowHeight - anchorTop - anchorHeight;
    var anchorRight = windowWidth - anchorLeft - anchorWidth;

    // 触发元素相对其拥有定位属性的父元素的位置
    var anchorOffsetTop = $anchor[0].offsetTop;
    var anchorOffsetLeft = $anchor[0].offsetLeft;

    // ===============================
    // ================= 自动判断菜单位置
    // ===============================
    if (_this.options.position === 'auto') {

      // 判断下方是否放得下菜单
      if (anchorBottom + (isCovered ? anchorHeight : 0) > menuHeight + gutter) {
        position = 'bottom';
      }

      // 判断上方是否放得下菜单
      else if (anchorTop + (isCovered ? anchorHeight : 0) > menuHeight + gutter) {
        position = 'top';
      }

      // 上下都放不下，居中显示
      else {
        position = 'center';
      }
    } else {
      position = _this.options.position;
    }

    // ===============================
    // ============== 自动判断菜单对齐方式
    // ===============================
    if (_this.options.align === 'auto') {

      // 判断右侧是否放得下菜单
      if (anchorRight + anchorWidth > menuWidth + gutter) {
        align = 'left';
      }

      // 判断左侧是否放得下菜单
      else if (anchorLeft + anchorWidth > menuWidth + gutter) {
        align = 'right';
      }

      // 左右都放不下，居中显示
      else {
        align = 'center';
      }
    } else {
      align = _this.options.align;
    }

    // ===============================
    // ==================== 设置菜单位置
    // ===============================
    if (position === 'bottom') {
      transformOriginY = '0';

      menuTop =
        (isCovered ? 0 : anchorHeight) +
        (isFixed ? anchorTop : anchorOffsetTop);

    } else if (position === 'top') {
      transformOriginY = '100%';

      menuTop =
        (isCovered ? anchorHeight : 0) +
        (isFixed ? (anchorTop - menuHeight) : (anchorOffsetTop - menuHeight));

    } else {
      transformOriginY = '50%';

      // =====================在窗口中居中
      // 显示的菜单的高度，简单菜单高度不超过窗口高度，若超过了则在菜单内部显示滚动条
      // 级联菜单内部不允许出现滚动条
      var menuHeightTemp = menuHeight;

      // 简单菜单比窗口高时，限制菜单高度
      if (!_this.isCascade) {
        if (menuHeight + gutter * 2 > windowHeight) {
          menuHeightTemp = windowHeight - gutter * 2;
          _this.$menu.height(menuHeightTemp);
        }
      }

      menuTop =
        (windowHeight - menuHeightTemp) / 2 +
        (isFixed ? 0 : (anchorOffsetTop - anchorTop));
    }

    _this.$menu.css('top', menuTop + 'px');

    // ===============================
    // ================= 设置菜单对齐方式
    // ===============================
    if (align === 'left') {
      transformOriginX = '0';

      menuLeft = isFixed ? anchorLeft : anchorOffsetLeft;

    } else if (align === 'right') {
      transformOriginX = '100%';

      menuLeft = isFixed ?
        (anchorLeft + anchorWidth - menuWidth) :
        (anchorOffsetLeft + anchorWidth - menuWidth);
    } else {
      transformOriginX = '50%';

      //=======================在窗口中居中
      // 显示的菜单的宽度，菜单宽度不能超过窗口宽度
      var menuWidthTemp = menuWidth;

      // 菜单比窗口宽，限制菜单宽度
      if (menuWidth + gutter * 2 > windowWidth) {
        menuWidthTemp = windowWidth - gutter * 2;
        _this.$menu.width(menuWidthTemp);
      }

      menuLeft =
        (windowWidth - menuWidthTemp) / 2 +
        (isFixed ? 0 : anchorOffsetLeft - anchorLeft);
    }

    _this.$menu.css('left', menuLeft + 'px');

    // 设置菜单动画方向
    _this.$menu.transformOrigin(transformOriginX + ' ' + transformOriginY);
  }
916380
function () {

    function getRider() {
      if (process.env.LIGHTSQLSERVER_HOST) {
        return sqlserverRider;
      }
      if (process.env.LIGHTMYSQL_HOST) {
        return mysqlRider;
      }
      return mongoRider;
    }

    // 遍历所有board，以class名注册类，并添加board方法
    this.board.forEach(item => {
      this[item.class] = this[item.class] || {};

      log.debug(`>>>> ${item.api} ${item.class} ${item.action} ${CONST.METHOD[item.type]}`);

      this[item.class][item.action] = (handler, params, callback) => {

        // params参数未指定
        if (typeof params === 'function') {
          callback = params;
          params = undefined;
        }

        // 添加参数
        handler = handler.copy(params || handler.params);
        handler.api = item;

        const func = getRider()[CONST.BOARD_TYPE[item.type]];
        if (func) {
          return func.call(this, handler, callback);
        }

        log.debug('no method. ' + item.class + '#' + item.action);
        callback(new error.class.MethodNotFoundError());
      };
    });
  }
913886
function ScreenClickedEvent(){
        $this->waitAnswer();
        $data = $this->request->getData();
        $url = isset($data['request']['token']) ? $data['request']['token'] : '';
        if(!$url){
            $this->setExpectSpeech(false);
            return;
        }

        $token = $this->decodeToken($url);
        $page = isset($token['page']) ? $token['page'] : '';
        //item 是当前页面
        $item = isset($token['item']) ? $token['item'] : '';

        if($page == 'home' && $item == 'video'){
            return $this->videoIntent(); 
        }
        if($page == 'home' && $item == 'audio'){
            return $this->audioIntent(); 
        }
        if($page == 'video'){
            //page如果不为home，item则存的是id
            $directives = $this->getVideoPlay($item);
            return [
                'directives' => $directives
            ]; 
        }
        if($page == 'audio'){
            $directives = $this->getAudioPlay($item); 
            return [
                'directives' => $directives
            ]; 
        }
    }
1121257
protected function viewRender()
    {
        if (!$this->container->has('view')) {
            return null;
        }

        // 视图实例
        $view = $this->view;

        // 禁止自动渲染视图
        if ($view->isDisabled()) {
            return null;
        }

        // 获取模版文件路径
        $controller = $this->dispatcher->getHandlerName();
        $action     = $this->dispatcher->getActionName();
        $template   = "$controller/$action";

        // 将 Flash 服务添加到 View
        $view->setVar('flash', $this->flash);

        // 自动渲染视图
        return $view->render($template);
    }
73680
function __init(opts) {
    //扩展参数
    extend(this.options, opts || (opts = {}));
    //获取目标元素
    this.appearWatchElements = this.appearWatchElements || __getElements.call(this, '.' + this.options.cls);
    //初始化位置信息
    __initBoundingRect.call(this, this.appearWatchElements);
    //绑定事件
    __bindEvent.call(this);
  }
277680
private function getCsrfHtml()
    {
        $html =  '<input type="hidden" name="_token" value="'.$this->getCsrfToken().'">';
        /**
         * 隐藏表单的html传递给前端
         */
        $this->vitex->res->set('csrf_token_html',$html);
        return $html;
    }
683782
function beforeCreate () { // eslint-disable-line no-inner-declarations
    // 将 element 挂到 vue 下方便使用
    this.$element = element

    this.$emit = function emit (eventName, ...args) {
      customEmit(element, eventName, ...args)
      viewer.eventAction.execute(eventName, element, ...args)
      this.__proto__ && this.__proto__.$emit.call(this, eventName, ...args) // eslint-disable-line no-proto
    }

    this.$on = function on (eventName, callback) {
      this.__proto__ && this.__proto__.$on.call(this, eventName, callback) // eslint-disable-line no-proto
      element.customElement.addEventAction(eventName, callback)
    }
  }
465824
function getHtmlContent(jQuery, fileArr, urlFunc, scriptAttr) {
    var $ = jQuery,
        jsArr = [],
        cssArr = [];

    // 获得js和css文件数组
    fileArr.forEach(function (item) {
        var extName = path.extname(item.filePathInHtml);
        switch (extName) {
            case '.js':
                jsArr.push(item);
                break;
            case '.css':
                cssArr.push(item);
                break;
            default :
                break;
        }
    });

    //处理JS
    if (jsArr.length) {
        var scriptDomArr = $('script[' + scriptAttr + ']');

        scriptDomArr.each(function () {
            var scriptDom = $(this),
                scriptUrl = scriptDom.attr(scriptAttr);

            if (!util.isExternalUrl(scriptUrl)) {
                for (var i = 0, length = jsArr.length; i < length; i++) {
                    var one = jsArr[i];

                    if (util.isMatch(scriptUrl, one.filePathInHtml)) {
                        urlFunc(scriptDom, scriptUrl, one, scriptAttr);

                        if (scriptAttr === "data-main") {
                            dataMainUrl = scriptUrl;
                        }

                        break;
                    }
                }
            }
        });

    }

    //处理CSS
    if (cssArr.length) {
        var cssDomArr = $('link[rel="stylesheet"][href]');

        cssDomArr.each(function () {
            var cssDom = $(this),
                cssUrl = cssDom.attr('href');

            if (!util.isExternalUrl(cssUrl)) {
                for (var i = 0, length = cssArr.length; i < length; i++) {
                    var one = cssArr[i];

                    if (util.isMatch(cssUrl, one.filePathInHtml)) {
                        urlFunc(cssDom, cssUrl, one, 'href');
                        break;
                    }
                }
            }
        });
    }

    return $.html();
}
1329621
public function getJsapiTicketFromWechat()
    {
        $wechat_jsapi_url = 'https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token='.$this->getAccessToken();
        $client = new Client();
        $json = $client->get($wechat_jsapi_url)->getBody();
        $arr = json_decode($json, true);

        if(array_has($arr, 'errcode') && (array_get($arr, 'errcode') == 4001 || array_get($arr, 'errcode') == 4002)){
            $this->getAccessTokenFromWechat();
            $this->getJsapiTicket();
        }else{
            $jsapi_ticket = $arr['ticket'];
            $expire = $arr['expires_in'];
            ServerVal::updateOrCreate(['var_name' => 'jsapi'], ['var_value'=> $jsapi_ticket, 'expire'=>$expire, 'var_up_time' => time()]);
            return $arr['ticket'];
        }

    }
671006
public function getFormInitializationJavaScriptCode()
    {
        $formName = GeneralUtility::quoteJSvalue($this->getFormObject()->getName());
        $formConfigurationJson = $this->handleFormConfiguration($this->getFormConfiguration());

        $javaScriptCode = <<<JS
(function() {
    Fz.Form.register($formName, $formConfigurationJson);
})();
JS;

        return $javaScriptCode;
    }
681938
public function getComonentTicket()
    {
        $receive = new WechatReceive(array(
            'appid'          => $this->component_appid,
            'appsecret'      => $this->component_appsecret,
            'encodingaeskey' => $this->component_encodingaeskey,
            'token'          => $this->component_token,
            'cachepath'      => Cache::$cachepath
        ));
        # 会话内容解密状态判断
        if (false === $receive->valid()) {
            $this->errCode = $receive->errCode;
            $this->errMsg = $receive->errMsg;
            Tools::log("Get Wechat Push ComponentVerifyTicket Faild. {$this->errMsg} [$this->errCode]", "ERR - {$this->authorizer_appid}");
            return false;
        }
        $data = $receive->getRev()->getRevData();
        if ($data['InfoType'] === 'component_verify_ticket' && !empty($data['ComponentVerifyTicket'])) {
            # 记录推送日志到微信SDK
            Tools::log("Wechat Push ComponentVerifyTicket Success. ");
            Tools::setCache('component_verify_ticket', $data['ComponentVerifyTicket']);
        }
        return $data;
    }