WebAction.php 19.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
<?php

/**
 * 所有Controller控制器的基类
 * 
 * @name AbstractAction
 * @package library
 * @copyright yoho.inc
 * @version 1.0 (2015-9-15 11:55:25)
 * @author fei.hong <fei.hong@yoho.cn>
 */

namespace Action;

use Yaf\Controller_Abstract;
use Yaf\Dispatcher;
use WebPlugin\Cache;
use WebPlugin\Helpers;
use Hood\Session;
use WebPlugin\Mobile;
use Api\Yohobuy;
use LibModels\Web\Passport\LoginData;
use WebPlugin\UdpLog;

class WebAction extends Controller_Abstract
{

    /**
     * HTTP请求对象
     * 
     * @var object 
     */
    protected $_request;

    /**
     * 用户相关信息
     */
    protected $_vip;
    protected $_uid = 0;
    protected $_uname = '';
    protected $_usession = '';
    protected $_useSession = true;

    /**
     * 存放模板数据
     * 
     * @var array 
     */
    protected $_data;

    /**
     * 初始化
     */
    public function init()
    {
        $isAjax = $this->isAjax();
        if (!$isAjax) {
            Mobile::isGoMobile();
        }

        $this->_request = $this->getRequest();

        // 设置环境变量
        switch (APPLICATION_ENV) {
            case 'production': // 生产
                $this->_view->assign('rlsEnv', true);
                $this->_useSession = true;
                break;
            case 'preview':      // 预览
                $this->_view->assign('preEnv', true);
                $this->_useSession = true;
                break;
            case 'testing':      // 测试
                $this->_view->assign('testEnv', true);
                $this->_useSession = true;
                break;
            case 'develop':      // 开发
            default:
                $this->_view->assign('devEnv', true);
                $this->_useSession = true;
                break;
        }

        //自动登录
        if (!$isAjax) {
            $this->autoLogin();
        }
    }

    /**
     * 自动登录 
     */
    protected function autoLogin()
    {
        $uid = $this->getUid(true);
        $isRemember = $this->getCookie('isRemember');
        $accountKey = $this->getCookie('remem');
        if (!$uid && $isRemember && $accountKey) {
            $accountInfo = $this->getCache($accountKey);
            $shoppingKey = Helpers::getShoppingKeyByCookie();
            $res = LoginData::signin($accountInfo['area'], $accountInfo['account'], $accountInfo['password'], $shoppingKey);
            if (isset($res['code']) && $res['code'] == 200 && !empty($res['data']['uid'])) {
                $refer = rawurldecode($this->getCookie('refer', ''));
                if (empty($refer) || strstr($refer, 'signin.html') || strstr($refer, 'passport/')) {
                    $refer = SITE_MAIN;
                }
                $this->syncUserSession($res['data']['uid']);
                $this->go($refer);
            }
            else {
                //登录失败-清空remem
                $this->setCookie('isRemember', false);
                $this->setCookie('remem', '');
            }
        }
    }

    /**
     * 封装一下获取get参数
     * 
     * @param String $key
     * @param mixed $default
     * @return mixed
     */
    protected function get($key = null, $default = null)
    {
        if (null === $key) {
            return $_GET;
        }
        return $this->_request->getQuery($key, $default);
    }

    /**
     * 封装一下获取post参数
     * 
     * @param String $key
     * @param mixed $default
     * @return mixed
     */
    protected function post($key = null, $default = null)
    {
        if (null === $key) {
            return $_POST;
        }
        return $this->_request->getPost($key, $default);
    }

    /**
     * 封装一下获取YAF内部的参数
     * 
     * @param String $key
     * @param mixed $default
     * @return mixed
     */
    protected function param($key, $default = null)
    {
        return $this->_request->getParam($key, $default);
    }

    /**
     * 封装一下获取服务器的参数
     * 
     * @param String $key
     * @param mixed $default
     * @return mixed
     */
    protected function server($key, $default = null)
    {
        return $this->_request->getServer($key, $default);
    }

    /**
     * 关闭模板自动渲染
     * 
     * @return void
     */
    protected function disableView()
    {
        Dispatcher::getInstance()->autoRender(false);
    }

    /**
     * 输出JSON数据到浏览器
     * 
     * @return void
     */
    protected function echoJson($json)
    {
        headers_sent() || header('Content-Type: application/json; charset=utf-8;');

        if (is_array($json)) {
            $json = json_encode($json);
        }
        echo $json;
    }

    /**
     * 返回JSON数据
     * 
     * @param int $code 状态编码
     * @param string $message 提示信息
     * @param mixed $data 数据内容
     * @return json
     */
    protected function returnJson($code, $message, $data)
    {
        headers_sent() || header('Content-Type: application/json; charset=utf-8;');

        return json_encode(array(
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ));
    }

    /**
     * JSON输出
     * 
     * @param $code
     * @param string $message
     * @param mixed $data
     */
    protected function helpJsonResult($code, $message = '', $data = null)
    {
        header('Content-Type: application/json; charset=utf-8;');

        echo json_encode(array('code' => $code, 'message' => $message, 'data' => $data));
        exit();
    }

    /**
     * JSONP Callback输出, 用于远程调用
     * 
     * @param string $callbackString
     * @param int $code
     * @param string $message
     * @param mixed $data
     */
    protected function helpJsonCallbackResult($callbackString, $code, $message = '', $data = null)
    {
        header('Content-Type: application/json; charset=utf-8;');

        echo $callbackString, '(';
        echo json_encode(array('code' => $code, 'message' => $message, 'data' => $data));
        echo ')';
        exit();
    }

    /**
     * 判断是不是AJAX请求
     * 
     * @return bool
     */
    protected function isAjax()
    {
        return $this->_request->isXmlHttpRequest();
    }

    /**
     * 跳转到错误页面
     */
    protected function error()
    {
        headers_sent() || header('Location: /error.html');

        exit();
    }

    /**
     * 跳转到指定的URL
     * 
     * @param string $url 链接地址
     * @return void
     */
    protected function go($url)
    {
        headers_sent() || header('Location: ' . $url);

        exit();
    }

    /**
     * 设置Cookie
     * 
     * @param string  $name   cookie的名字
     * @param string  $value  cookie的值
     * @param integer $expire cookie过期时间
     * @param integer $path   cookie可用的路径
     * @param string  $domain cookie可用域名
     */
    protected function setCookie($name, $value, $expire = 0, $path = '/', $domain = '.yohobuy.com')
    {
        setcookie($name, $value, $expire, $path, $domain);
    }

    /**
     * 返回Cookie变量
     * 
     * @param  string $name    cookie名称
     * @param  string $default 未获取到返回的默认值
     * @return string          获取到的cookie值
     */
    protected function getCookie($name, $default = '')
    {
        return $this->_request->getCookie($name, $default);
    }

    /**
     * 设置缓存
     * 
     * @param string $key 键名
     * @param mixed $value 需要缓存的数据
     * @param int $expire 缓存有效期(单位秒, 0表示永久)
     * @return void
     */
    protected function setCache($key, $value, $expire)
    {
        Cache::set($key, $value, $expire);
    }

    /**
     * 获取缓存
     * 
     * @param string $key 键名
     * @param bool $isMaster 控制是到主服务器取,还是到从服务器取缓存
     * @return mixed
     */
    protected function getCache($key, $isMaster = true)
    {
        if ($isMaster) {
            return Cache::get($key, 'master');
        }
        else {
            return Cache::get($key, 'slave');
        }
    }

    /**
     * 设置Session
     * 
     * @param string $name 名称
     * @param mixed $value 值
     * @return void
     */
    public function setSession($name, $value)
    {
        if ($this->_useSession) {
            Session::start('www_yohobuy_session', null, 'yohobuy.com')->__set($name, $value);
        }
        else {
            Session::fileStart('www_yohobuy_session')->__set($name, $value);
        }
    }

    /**
     * 获取Session
     * 
     * @param string $name 名称
     * @return mixed
     */
    public function getSession($name)
    {
        if ($this->_useSession) {
            //windows
            if (DIRECTORY_SEPARATOR === '\\') {
                return Session::fileStart('www_yohobuy_session')->__get($name);
            }
            else {//linux
                return Session::start('www_yohobuy_session', null, 'yohobuy.com')->__get($name);
            }
        }
        else {
            return '';
        }
    }

    /**
     * 登录完成后置cookie-_UID,session
     */
    protected function syncUserSession($uid)
    {
        $userInfo = LoginData::profile($uid);
        if (isset($userInfo['data']) && $userInfo['data']) {
            $token = Helpers::makeToken($uid);
            $uidCookie = $userInfo['data']['profile_name'] . '::' . $userInfo['data']['uid'] . '::' . $userInfo['data']['vip_info']['title'] . '::' . $token;
            $this->setCookie('_UID',$uidCookie,time() + 86400 * 360);
            UdpLog::info('【登录】同步登陆cookie生成',$uidCookie);
        }
        $this->setSession('_TOKEN', $token);
        $this->setSession('_LOGIN_UID', $uid);
        $this->setSession('_SYS_USER_SESSION', 1);
        $this->setCookie('_TOKEN', $token);
    }

    /**
     * 获取当前登录的用户ID
     * 
     * @param bool $useSession (true:从服务端session中检查, false:从客户端cookie中检查)
     * @return int
     */
    protected function getUid($useSession = false)
    {
        // 控制是否启用SESSION
        if (!$this->_useSession) {
            $useSession = false;
        }
        //$useSession = false;

        if (!$this->_uid) {
            $cookie = $this->getCookie('_UID');
            // 兼容老的
            if (!empty($cookie)) {
                $cookieList = explode('::', $cookie);
                if (isset($cookieList[1]) && is_numeric($cookieList[1])) {
                    if ($useSession) {
                        $token = $this->getSession('_TOKEN');
                        if (empty($token)) {
                            $token = $this->getCookie('_TOKEN');
                        }
                        if ($token === Helpers::makeToken($cookieList[1])) {
                            $this->_uid = $cookieList[1];
                        }
                    }
                    else {
                        $this->_uid = $cookieList[1];
                    }
                    $this->_uname = $cookieList[0];
                    $this->_usession = $cookieList[3];
                    $this->_vip = $cookieList[2];
                }
            }
            // 新的, 如果老站没有同步成功,再尝试从SESSION获取
            elseif ($useSession) {
                $uid = $this->getSession('_LOGIN_UID');
                if (!empty($uid)) {
                    $this->_uid = $uid;
                }
            }
        }
        return $this->_uid;
    }

    /**
     * 获取客户端唯一标识
     * 
     * @return string
     */
    protected function getUdid()
    {
        $udid = $this->getCookie('suid');

        if (empty($udid)) {
            $realIP = $this->_request->getServer('HTTP_X_REAL_IP');
            if ($realIP) {
                $udid = md5($realIP);
            }
            else {
                $realIP = $this->_request->getServer('REMOTE_ADDR', '');
                $udid = md5($realIP);
            }
        }

        return $udid;
    }

    /*
     * 设置网站SEO的标题
     * 
     * @param string $title 标题
     * @param string $sign 连接的字符串
     * @param bool $showMore 是否显示更多内容
     * @return void
     */

    protected function setTitle($title, $showMore = false, $sign = '')
    {
        $this->_view->assign('title_more', $showMore);
        $this->_view->assign('title', $title . $sign);
    }

    /**
     * 设置网站SEO的关键词
     * 
     * @param string $keywords 关键词,多个之间用","逗号分隔
     * @param bool $showMore 是否显示更多内容
     * @param string $sign 连接的字符串
     * @return void
     */
    protected function setKeywords($keywords, $showMore = false, $sign = '')
    {
        $this->_view->assign('keywords_more', $showMore);
        $this->_view->assign('keywords', rtrim($keywords, ',') . $sign);
    }

    /**
     * 设置网站SEO的描述内容
     * 
     * @param string $description  描述内容
     * @param bool $showMore 是否显示更多内容
     * @param string $sign 连接的字符串
     * @return void
     */
    protected function setDescription($description, $showMore = false, $sign = '')
    {
        $this->_view->assign('description_more', $showMore);
        $this->_view->assign('description', $description . $sign);
    }

    /**
     * 设置最后修改时间
     * 
     * @param string $modifiedTime 修改时间戳
     * @param type $notModifiedExit 是否在没有修改时返回304状态
     * @return void
     */
    public static function setLastModified($modifiedTime, $notModifiedExit = true)
    {
        $modifiedTime = date('D, d M Y H:i:s ', $modifiedTime) . 'GMT';
        if ($notModifiedExit && isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $modifiedTime == $_SERVER['HTTP_IF_MODIFIED_SINCE']) {
            header('HTTP/1.1 304 Not Modified');
            exit();
        }
        header('Last-Modified: ' . $modifiedTime);
    }

    /**
     * 设置浏览器的缓存
     * 
     * @param int $seconds 单位是秒
     * @return void
     */
    public static function setExpires($seconds = 180)
    {
        $time = date('D, d M Y H:i:s ', time() + $seconds) . 'GMT';

        header('Expires: ' . $time);
    }

    /**
     * 设置头部
     * 
     * @param string $channel (默认不设置)
     * @return 
     */
    protected function setWebNavHeader($channel = '')
    {
        $uid = $this->getUid(true);
        //是否同步了session
        $sysUserSession = intval($this->getSession('_SYS_USER_SESSION'));
        //同步session时间
        $sysUserSessionTime = $this->getSession('_SYS_USER_SESSION_TIME');
        if(empty($sysUserSession)) {
            $sysUserSession = 1;
        }
        if(empty($sysUserSessionTime)) {
            $sysUserSessionTime = 0;
        }
        if (!empty($channel)) {//设置频道
            //\Index\HomeModel::setSwitchToCookie($channel);
        }
        else {
            $channel = \Index\HomeModel::getSwitchChannel();
        }
        $apiDomain = $this->getApiDomain();
        $header = array(
            'navbars' => \Index\HomeModel::getNavBars($channel),
            'gobytype' => 'gobuy' . $channel,
            'searchcate' => 'searchcate' . $channel,
            'header' => true,
            'apiDomain' => $apiDomain,
            'sysUserSession'=> '',
        );
        //同步session
        if(!empty($uid) && $sysUserSession < 20) {
            $header['sysUserSession'] = Helpers::syncUserSession($uid);
            $sysUserSession = $sysUserSession + 1;
            $this->setSession('_SYS_USER_SESSION', $sysUserSession);
            $this->setSession('_SYS_USER_SESSION_TIME', time());
        } //一个小时同步一次
        else if(!empty($uid) && (time() - $sysUserSessionTime) >= 3600) {
            $this->setSession('_SYS_USER_SESSION', 0);
        }
        else if(empty($uid) && $sysUserSession >= 20) {
            $this->setSession('_SYS_USER_SESSION', 0);
        } 

        $this->_view->assign('headerdata', $header);
    }

    /**
     * 默认简单头部
     * 
     * @return array
     */
    public function setSimpleHeader()
    {
        //拼接简单头部
        $radomNum = time();
        $apiDomain = $this->getApiDomain();
        $this->_view->assign('simpleHeader', array(
            'logo' => array(
                'img' => 'http://static.yohobuy.com/newheader/img/logo_e.png',
                'url' => SITE_MAIN
            ),
            'tool' => array(
                'favoriteHref' => Helpers::url('/home/favorite?t=' . $radomNum), //我的收藏链接
                'couponHref' => Helpers::url('/home/coupons?t=' . $radomNum), //我的优惠券链接
                'orderHref' => Helpers::url('/home/orders?t=' . $radomNum), //订单中心连接
                'userCenter' => Helpers::url('/home?t=' . $radomNum),
                'helpHref' => Helpers::url('/help'),
                'loginHref' => Helpers::url('/signin.html'), //登录链接,已登录不传
                'registerHref' => Helpers::url('/reg.html'), //注册链接,已登录不传
            ),
            'simpleHeader' => true,
            'apiDomain' => $apiDomain,
        ));
    }

    /**
     * 通过当前用户审判是否跳到登录
     *
     * @param int $useSession (true:从服务端session中检查, false:从客户端cookie中检查)
     * @param null|string $refer 访问来源地址
     * @return uid/跳转链接
     */
    protected function auditJumpLogin($useSession = true, $refer = null)
    {
        $uid = $this->getUid($useSession);
        if (!$uid) {
            if (empty($refer)) {
                $refer = $this->server('HTTP_REFERER', SITE_MAIN);
            }
            $this->go(Helpers::url('/signin.html', array('refer' => $refer)));
        }
        else {
            return $uid;
        }
    }

    /**
     * 获取登录接口域名
     * @return string
     */
    protected function getApiDomain()
    {
        if (APPLICATION_ENV == 'production' || APPLICATION_ENV == 'preview') {
            $apiDomain = Yohobuy::API_LOGIN_URL;
        }
        else {
            $apiDomain = Yohobuy::API_LOGIN_URL_TEST;
        }
        return $apiDomain;
    }

    /**
     * JS 跳转并提示
     *
     * @param String $message 提示信息
     * @param String $expression 附加的JS
     * @return void
     */
    protected function helpJsRedirect($message = '', $expression = "history.back()")
    {
        header("content-type: text/html; charset=utf-8");

        if ($message != '') {
            $message = strtr(addslashes($message), array('\n' => '\\n'));
            echo "<script language=\"javascript\">";
            echo "alert(\"{$message}\");";
            echo "</script>";
        }

if ($expression === 'history.back()') {
$expression = '';
echo <<<EOF
<script language="javascript">
    if (navigator.userAgent.indexOf('MSIE') >= 0 && history.length > 0) {
        window.history.go( -1 ); 
    } else if (history.length > 1) {
        window.history.go( -1 );
    } else {
        window.opener = null;
        window.close();
    }
</script>
EOF;
}
        if ($expression != '') {
            echo "<script language=\"javascript\">\n";
            echo $expression . "\n";
            echo "</script>";
        }
        exit();
    }

}