Phalcon Framework 1.3.4

Phalcon\Cache\Exception: Cannot connect to Memcached server

/home/123i/website/infra/RegisterListeners/RegisterSessionListener.php (48)
#0Phalcon\Cache\Backend\Memcache->_connect()
#1Phalcon\Cache\Backend\Memcache->get(2664a08c09b9d5fe194742642531a4e1, 43200)
#2Phalcon\Session\Adapter\Memcache->read(2664a08c09b9d5fe194742642531a4e1)
#3Phalcon\Session\Adapter->start()
<?php
 
namespace Infra\RegisterListeners;
 
/**
 *
 * Registra o serviço de CDN
 *
 * @package Infra
 * @author 123i Team
 *
 **/
class RegisterSessionListener
{
    /**
     * Inicializa os serviços de Session
     *
     * @param $di
     * Dependence Injetion Manager do Phalcon
     *
     *
     * @param $extension
     * Extensão do arquivo que sobrescreve as configurações com extensão .global
     * no caso de testes passamos o parametro como 'test', possibilidades atuais ('local', 'test', 'global')
     */
    public static function init(\Phalcon\DI $di,  $extension = 'local')
    {
        //se estiver rodando testes
        if($extension == 'test'){
            if(!file_exists(__DIR__ . '/../config/session.test.php')){
                throw new \Exception("Arquivo session.test.php nao existe");
                
            }
        }
        
        //verifica configuracoes locais
        $config = include file_exists(__DIR__.'/../config/session.'.$extension.'.php')? __DIR__.'/../config/session.'.$extension.'.php' : __DIR__.'/../config/session.global.php';
 
        if (isset($config['session']) && $config['session']) {
 
            foreach ($config['session'] as $k => $session) {
                $sessionName = 'session_'.$k;
 
                $di->setShared($sessionName, function() use ($session) {
 
                    //sessiond connection settings
                    $session = new \Phalcon\Session\Adapter\Memcache($session);
                    $session->start();
                    return $session;
 
                });
 
            }
        }
    }
}
 
#4Infra\RegisterListeners\RegisterSessionListener::Infra\RegisterListeners\{closure}()
#5Phalcon\DI\Service->resolve(null, Object(Phalcon\DI\FactoryDefault))
#6Phalcon\DI->get(session_www)
<?php
namespace Application\Controller;
 
use BaseDomain\Services\RecognizeUrlService;
use Phalcon\Http\Request;
use Phalcon\Mvc\Controller;
 
/**
 *  \Phalcon\Mvc\Controller has a final __construct() method, so we can't
 *  extend the constructor (which we will need for our RESTController).
 *  Thus we extend DIInjectable instead.
 */
class BaseController extends Controller
{
 
    public function initialize()
    {
 
        $this->view->setLayoutsDir('../../../Application/view/layouts/');
        $this->view->setLayout('layout');
        $this->in123i = true;
        if (isset($_SERVER['HTTP_AMBIENTE']) || isset($_GET['uolHost'])) {
            $this->in123i = false;
            $this->view->setVar('uolHost', true);
        }
        if ($this->in123i === false) {
            $this->base_url_www = 'https://123i.uol.com.br';
            // $this->base_url_api = 'http://api.123i.com.br';
        }
        if(
            isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && 
            $_SERVER['HTTP_X_FORWARDED_PROTO'] != 'https' && 
            isset($_SERVER['HTTP_AMBIENTE']) && 
            $_SERVER['HTTP_AMBIENTE'] == '123i.uol.com.br'
        ){
            $this->redirectToUrl('https://123i.uol.com.br'.$_SERVER['REQUEST_URI'], 301);
        }
        $this->view->setVar('base_url_www', $this->base_url_www);
        $this->view->setVar('base_url_login', 'https://meu.123i.com.br');
        $this->view->setVar('base_url_www2', $this->base_url_www2);
        $this->view->setVar('base_url_api', $this->base_url_api);
        $this->view->setVar('base_url_oauth2', $this->base_url_oauth2);
        $this->view->setVar('base_url_cdn', $this->base_url_cdn);
        $this->view->setVar('base_url_blog', $this->base_url_blog);
        $this->view->setVar('base_url_map', $this->base_url_map);
 
        $leadOrigin   = $this->request->get('utm_source');
        $leadMedium   = $this->request->get('utm_medium');
        $leadCampaign = $this->request->get('utm_campaign');
        $leadContent  = $this->request->get('utm_content');
        $gclid        = $this->request->get('gclid');
 
        $ads = $this->setLeadOrigin($leadOrigin, $leadMedium, $leadCampaign, $leadContent, $gclid);
 
        if (is_null($ads) || $ads['origin'] == null) {
            $ads = $this->setReferer();
        }
        $this->logged();
 
        $this->view->setVar('ads', $ads);
        $this->view->setVar('isOrganic', $this->isOrganic());
        $this->view->setVar('cookieUser', $this->cookieUser());
 
    }
 
    protected function whatAb($name, $percent = 1)
    {
        $name = 'rab_' . $name;
        $this->cookies->useEncryption(false);
        if (isset($_COOKIE[$name])) {
            return $_COOKIE[$name];
        }
        $ab = rand(1, 10) > $percent ? 'a' : 'b';
        setcookie($name, $ab, time() + 2592000);
        return $ab;
    }
 
    private function logged()
    {
        $this->session = $this->di->get('session_www');
        if ($user = $this->session->get('userLogged')) {
            $this->userLogged = $user;
            $this->view->setVar('userLogged', $user);
        }
    }
 
    private function setReferer()
    {
        if (isset($_SERVER['HTTP_REFERER'])) {
            if (strstr($_SERVER['HTTP_REFERER'], 'google')) {
                return ['origin' => 'google-search', 'active' => 0, 'medium' => null, 'campaign' => null, 'content' => null];
            }
            if (strstr($_SERVER['HTTP_REFERER'], 'bing')) {
                return ['origin' => 'bing-search', 'active' => 0, 'medium' => null, 'campaign' => null, 'content' => null];
            }
            if (strstr($_SERVER['HTTP_REFERER'], 'yahoo')) {
                return ['origin' => 'yahoo-search', 'active' => 0, 'medium' => null, 'campaign' => null, 'content' => null];
            }
            if (strstr($_SERVER['HTTP_REFERER'], 'facebook')) {
                return ['origin' => 'facebook-referral', 'active' => 0, 'medium' => null, 'campaign' => null, 'content' => null];
            }
        }
        return [
            'origin'   => 'organic',
            'active'   => 0,
            'medium'   => null,
            'campaign' => null,
            'content'  => null,
        ];
    }
    private function setLeadOrigin(
        $leadOrigin = null,
        $leadMedium = null,
        $leadCampaign = null,
        $leadContent = null,
        $gclid = null
    ) {
        if (strlen($gclid) > 0) {
            $leadOrigin = 'google';
        }
        $leadOrigin = strtolower($leadOrigin);
        $this->cookies->useEncryption(false);
 
        if ($this->cookies->has('123i_ads') && (is_null($leadOrigin)) || strlen($leadOrigin) == '') {
 
            // Get the cookie
            $ads = $this->cookies->get('123i_ads');
 
            // Get the cookie's value
            $value = json_decode($ads->getValue(), true);
 
            return $value;
 
        }
 
        if (isset($_GET['debug_origin'])) {
            var_dump($leadOrigin);
            var_dump($this->cookies->has('123i_ads'), json_decode($this->cookies->get('123i_ads')->getValue(), true));
            die();
        }
        if (isset($_COOKIE['ads']) && (is_null($leadOrigin) || strlen($leadOrigin) == 0)) {
            $value = json_decode($_COOKIE['ads'], true);
            return $value;
        }
 
        $config['ads'] = [
            'google'           => 'google',
            'uol'              => 'uol',
            'mitula'           => 'mitula',
            'nestoria'         => 'nestoria',
            'trovit'           => 'trovit',
            'email'            => 'email',
            'facebook'         => 'facebook',
            'criteo'           => 'criteo',
            'emktio'           => 'fulfilling',
            'facebook-webpush' => 'fulfilling',
            'push'             => 'fulfilling',
            'webpush'          => 'fulfilling',
            'fulfilling'       => 'fulfilling',
            'ffid'             => 'fulfilling',
            'hermes'           => 'fulfilling',
        ];
 
        if ($leadOrigin && isset($config['ads'][$leadOrigin])) {
            $ads = [
                'origin'   => $config['ads'][$leadOrigin],
                'active'   => 1,
                'medium'   => $leadMedium,
                'campaign' => $leadCampaign,
                'content'  => $leadContent,
            ];
 
        } else {
 
            $ads = [
                'origin'   => 'organic',
                'active'   => 0,
                'medium'   => null,
                'campaign' => null,
                'content'  => null,
            ];
        }
 
        //$this->cookies->delete('ads');
        //setcookie('ads', json_encode($ads), time() + 2592000, '/', '.123i.com.br');
 
        $x = setcookie('ads', json_encode($ads), time() + 2592000, '/', '.123i.uol.com.br');
        // var_dump($x);
        // die();
 
        $this->cookies->set('123i_ads', json_encode($ads), time() + 2592000);
 
        return $ads;
    }
    /**
     * undocumented function
     *
     * @return void
     * @author
     **/
    public function recognizeUrl($params, $validate = true)
    {
        $type = 'offer';
        if ($params['goal'] == 'shipping') {
            $type = 'new';
        }
 
        if ($params['goal'] == 'catalog') {
            $type = 'used';
        }
        if (strstr($_SERVER['REQUEST_URI'], 'lancamentos-comerciais')) {
            $type                    = 'newCommercial';
            $params['is_commercial'] = 1;
        };
        if (strstr($_SERVER['REQUEST_URI'], 'lancamentos-minha-casa-minha-vida')) {
            $type              = 'newMcmv';
            $params['is_mcmv'] = 1;
        };
 
        $page = $this->request->get('p') ? $this->request->get('p') : 1;
        if ($page > 1) {
            $params['page'] = $page;
        }
        $this->verifyRedirect();
 
        $recognizeUrl = RecognizeUrlService::start($type);
        $params       = $recognizeUrl->run($params);
 
        if ($validate) {
            if ($params['isValid'] === false) {
                if (isset($params['currentUrl']) && $params['currentUrl']) {
                    return $this->redirectToUrl($params['currentUrl']);
                }
                $this->set404();
            }
        }
 
        return $params;
    }
 
    /**
     * 404
     * @todo colocar em serviço
     * @return void
     * @author Ariana Kataoka
     **/
    public function set404()
    {
        $response = new \Phalcon\Http\Response();
 
        //Set status code
        $response->setStatusCode(404, 'Not Found');
        $response->setContent("Sorry, the page doesn't exist");
        $response->send();
        $this->view->render('index', 'notFound');
 
        $this->view->finish();
        echo $this->view->getContent();
        die();
    }
 
    /**
     * @todo colocar em serviço
     **/
    protected function set401()
    {
        $response = new \Phalcon\Http\Response();
        $response->setStatusCode(401, 'Unauthorized');
        $response->send();
        die();
    }
 
    /**
     * @todo colocar em serviço
     **/
    protected function setDownloadCsv($content)
    {
        $response = new \Phalcon\Http\Response();
        $response->setHeader("Content-Type", "text/csv");
        $response->setStatusCode(200, 'OK');
        $response->setContent($content);
        $response->send();
        die();
    }
 
    protected function setDownloadTar($content)
    {
        $response = new \Phalcon\Http\Response();
        $response->setHeader("Content-Type", "application/octet-stream");
        $response->setHeader("Content-Description:", "File Transfer");
        $response->setStatusCode(200, 'OK');
        $response->setContent($content);
        $response->send();
        die();
    }
 
    /**
     * Verifica se a url será redirecionada
     *
     * @return void
     * @author Raphael Giovanini
     **/
    public function verifyRedirect()
    {
        $urlActual = $this->request->getUri();
 
        $redirect = false;
 
        if (substr($urlActual, -9) == '/-/-/-/-/') {
            $this->redirectToUrl(str_replace('/-/-/-/-/', '', $urlActual));
        }
        if (substr($urlActual, -8) == '/-/-/-/-') {
            $this->redirectToUrl(str_replace('/-/-/-/-', '', $urlActual));
        }
        if (substr($urlActual, -7) == '/-/-/-/') {
            $this->redirectToUrl(str_replace('/-/-/-/', '', $urlActual));
        }
        if (substr($urlActual, -6) == '/-/-/-') {
            $this->redirectToUrl(str_replace('/-/-/-', '', $urlActual));
        }
        if (substr($urlActual, -5) == '/-/-/') {
            $this->redirectToUrl(str_replace('/-/-/', '', $urlActual));
        }
        if (substr($urlActual, -4) == '/-/-') {
            $this->redirectToUrl(str_replace('/-/-', '', $urlActual));
        }
        if (substr($urlActual, -3) == '/-/') {
            $this->redirectToUrl(str_replace('/-/', '', $urlActual));
        }
        if (substr($urlActual, -2) == '/-') {
            $this->redirectToUrl(str_replace('/-', '', $urlActual));
        }
        if (substr($urlActual, -1) == '/') {
            $this->redirectToUrl(substr($urlActual, 0, strlen($urlActual) - 1));
        }
 
    }
    /**
     * Redirecionar
     *
     * @return void
     * @author Raphael Giovanini
     **/
    public function redirectToUrl($url, $status = 302)
    {
        $response = new \Phalcon\Http\Response();
        $response->redirect($url, true, $status);
        $response->send();
        die();
    }
 
    public function newOrReturn($c = 'returned'){
        if ($this->cookies->has('userUniqueType')) {
            // Get the cookie
            $c = $this->cookies->get('userUniqueType');
        } elseif (isset($_COOKIE['userUniqueType']) && strlen($_COOKIE['userUniqueType']) > 0) {
 
            $c = $_COOKIE['userUniqueType'];
        }
        $this->cookies->set('userUniqueType', (string) $c, time() + 500);
        $this->view->setVar('cookieUserType', (string) $c);  
    }
    /**
     * Setar cookie de navegação para o usuário
     *
     * @return string
     * @author Raphael Giovanini
     **/
    public function cookieUser()
    {
        if ($this->cookies->has('userUnique')) {
            // Get the cookie
            $this->newOrReturn('returned');
            return $this->cookies->get('userUnique');
        } elseif (isset($_COOKIE['userUnique']) && strlen($_COOKIE['userUnique']) > 0) {
            $this->newOrReturn('returned');
            return $_COOKIE['userUnique'];
        } else {
 
            $uuid = sha1(md5(uniqid(rand() + time(), true)));
            $this->cookies->set('userUnique', $uuid, time() + 2592000);
 
            setcookie('userUnique', $uuid, time() + 2592000, '/', '.123i.com.br');
 
            $this->newOrReturn('new');
            return $uuid;
        }
    }
 
    public function cachePage()
    {
        $cacheConfig = ['host' => '123i-mc1.xpg.net.br', 'port' => 11213];
        if (isset($_GET['utm_source']) && count($_POST) == 0) {
            return true;
        }
        if (class_exists('Memcached')) {
            $memcacheObj = new \Memcached();
            $memcacheObj->addServer($cacheConfig['host'], $cacheConfig['port']);
            $result = $memcacheObj->get('page_' . md5($_SERVER['REQUEST_URI']));
 
        } else {
 
            $memcache = new \Memcache;
            $memcache->connect($cacheConfig['host'], $cacheConfig['port']);
            $result = $memcache->get('page_' . md5($_SERVER['REQUEST_URI']));
 
        }
        if ($result) {
            die($result . '<!-- m -->');
        }
 
    }
 
    public function getContent($url, $r = true)
    {
        list($cache, $data, $cacheName) = \Infra\LoadersConfigs\ConfigCache::getCache('cache_model_medium', __METHOD__, func_get_args());
        if ($data) {
            return $data;
        }
 
        $url = str_replace('https', 'http', $url);
        $ch  = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $content = trim(curl_exec($ch));
        if (strlen($content) == 0 && $r) {
            $x = curl_getinfo($ch);
            curl_close($ch);
            if ($x['http_code'] === 302) {
                $content = $this->getContent($x['redirect_url'], false);
            }
        } else {
            curl_close($ch);
        }
 
        if ($content && is_object($cache)) {
            $cache->save($cacheName, $content);
        }
 
        return $content;
    }
    public function getApi($url)
    {
        list($cache, $data, $cacheName) = \Infra\LoadersConfigs\ConfigCache::getCache('cache_model_medium', __METHOD__, func_get_args());
        if ($data) {
            return $data;
        }
        $url = str_replace('https', 'http', $url);
 
        $ch = curl_init();
 
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $content = trim(curl_exec($ch));
 
        curl_close($ch);
 
        $content = json_decode($content, true);
 
        if ($content && is_object($cache)) {
            $cache->save($cacheName, $content);
        }
        return $content;
    }
 
    public function setDefaultPage($folder, $path)
    {
        $this->view->setLayout('map');
        $this->view->setVar('container', true);
        $this->view->setVar('skip_search', true);
 
        $overlay = \SeoDomain\OverlayService::start();
        $this->view->setVar('records', ['overlay' => [
            'column1' => $overlay->column1(),
            'column2' => $overlay->column2(),
            'column3' => $overlay->column3(),
        ],
        ]);
        $this->view->render($folder, $path);
        $this->view->finish();
        echo $this->view->getContent();
        die();
    }
 
    public function isOrganic()
    {
        if (isset($_SERVER['HTTP_REFERER'])) {
            $thereferer = strtolower($_SERVER['HTTP_REFERER']);
            // see if it comes from google
            if (strpos($thereferer, "google")) {
                return true;
            }
        }
        return false;
    }
}
#7Application\Controller\BaseController->logged()
<?php
namespace Application\Controller;
 
use BaseDomain\Services\RecognizeUrlService;
use Phalcon\Http\Request;
use Phalcon\Mvc\Controller;
 
/**
 *  \Phalcon\Mvc\Controller has a final __construct() method, so we can't
 *  extend the constructor (which we will need for our RESTController).
 *  Thus we extend DIInjectable instead.
 */
class BaseController extends Controller
{
 
    public function initialize()
    {
 
        $this->view->setLayoutsDir('../../../Application/view/layouts/');
        $this->view->setLayout('layout');
        $this->in123i = true;
        if (isset($_SERVER['HTTP_AMBIENTE']) || isset($_GET['uolHost'])) {
            $this->in123i = false;
            $this->view->setVar('uolHost', true);
        }
        if ($this->in123i === false) {
            $this->base_url_www = 'https://123i.uol.com.br';
            // $this->base_url_api = 'http://api.123i.com.br';
        }
        if(
            isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && 
            $_SERVER['HTTP_X_FORWARDED_PROTO'] != 'https' && 
            isset($_SERVER['HTTP_AMBIENTE']) && 
            $_SERVER['HTTP_AMBIENTE'] == '123i.uol.com.br'
        ){
            $this->redirectToUrl('https://123i.uol.com.br'.$_SERVER['REQUEST_URI'], 301);
        }
        $this->view->setVar('base_url_www', $this->base_url_www);
        $this->view->setVar('base_url_login', 'https://meu.123i.com.br');
        $this->view->setVar('base_url_www2', $this->base_url_www2);
        $this->view->setVar('base_url_api', $this->base_url_api);
        $this->view->setVar('base_url_oauth2', $this->base_url_oauth2);
        $this->view->setVar('base_url_cdn', $this->base_url_cdn);
        $this->view->setVar('base_url_blog', $this->base_url_blog);
        $this->view->setVar('base_url_map', $this->base_url_map);
 
        $leadOrigin   = $this->request->get('utm_source');
        $leadMedium   = $this->request->get('utm_medium');
        $leadCampaign = $this->request->get('utm_campaign');
        $leadContent  = $this->request->get('utm_content');
        $gclid        = $this->request->get('gclid');
 
        $ads = $this->setLeadOrigin($leadOrigin, $leadMedium, $leadCampaign, $leadContent, $gclid);
 
        if (is_null($ads) || $ads['origin'] == null) {
            $ads = $this->setReferer();
        }
        $this->logged();
 
        $this->view->setVar('ads', $ads);
        $this->view->setVar('isOrganic', $this->isOrganic());
        $this->view->setVar('cookieUser', $this->cookieUser());
 
    }
 
    protected function whatAb($name, $percent = 1)
    {
        $name = 'rab_' . $name;
        $this->cookies->useEncryption(false);
        if (isset($_COOKIE[$name])) {
            return $_COOKIE[$name];
        }
        $ab = rand(1, 10) > $percent ? 'a' : 'b';
        setcookie($name, $ab, time() + 2592000);
        return $ab;
    }
 
    private function logged()
    {
        $this->session = $this->di->get('session_www');
        if ($user = $this->session->get('userLogged')) {
            $this->userLogged = $user;
            $this->view->setVar('userLogged', $user);
        }
    }
 
    private function setReferer()
    {
        if (isset($_SERVER['HTTP_REFERER'])) {
            if (strstr($_SERVER['HTTP_REFERER'], 'google')) {
                return ['origin' => 'google-search', 'active' => 0, 'medium' => null, 'campaign' => null, 'content' => null];
            }
            if (strstr($_SERVER['HTTP_REFERER'], 'bing')) {
                return ['origin' => 'bing-search', 'active' => 0, 'medium' => null, 'campaign' => null, 'content' => null];
            }
            if (strstr($_SERVER['HTTP_REFERER'], 'yahoo')) {
                return ['origin' => 'yahoo-search', 'active' => 0, 'medium' => null, 'campaign' => null, 'content' => null];
            }
            if (strstr($_SERVER['HTTP_REFERER'], 'facebook')) {
                return ['origin' => 'facebook-referral', 'active' => 0, 'medium' => null, 'campaign' => null, 'content' => null];
            }
        }
        return [
            'origin'   => 'organic',
            'active'   => 0,
            'medium'   => null,
            'campaign' => null,
            'content'  => null,
        ];
    }
    private function setLeadOrigin(
        $leadOrigin = null,
        $leadMedium = null,
        $leadCampaign = null,
        $leadContent = null,
        $gclid = null
    ) {
        if (strlen($gclid) > 0) {
            $leadOrigin = 'google';
        }
        $leadOrigin = strtolower($leadOrigin);
        $this->cookies->useEncryption(false);
 
        if ($this->cookies->has('123i_ads') && (is_null($leadOrigin)) || strlen($leadOrigin) == '') {
 
            // Get the cookie
            $ads = $this->cookies->get('123i_ads');
 
            // Get the cookie's value
            $value = json_decode($ads->getValue(), true);
 
            return $value;
 
        }
 
        if (isset($_GET['debug_origin'])) {
            var_dump($leadOrigin);
            var_dump($this->cookies->has('123i_ads'), json_decode($this->cookies->get('123i_ads')->getValue(), true));
            die();
        }
        if (isset($_COOKIE['ads']) && (is_null($leadOrigin) || strlen($leadOrigin) == 0)) {
            $value = json_decode($_COOKIE['ads'], true);
            return $value;
        }
 
        $config['ads'] = [
            'google'           => 'google',
            'uol'              => 'uol',
            'mitula'           => 'mitula',
            'nestoria'         => 'nestoria',
            'trovit'           => 'trovit',
            'email'            => 'email',
            'facebook'         => 'facebook',
            'criteo'           => 'criteo',
            'emktio'           => 'fulfilling',
            'facebook-webpush' => 'fulfilling',
            'push'             => 'fulfilling',
            'webpush'          => 'fulfilling',
            'fulfilling'       => 'fulfilling',
            'ffid'             => 'fulfilling',
            'hermes'           => 'fulfilling',
        ];
 
        if ($leadOrigin && isset($config['ads'][$leadOrigin])) {
            $ads = [
                'origin'   => $config['ads'][$leadOrigin],
                'active'   => 1,
                'medium'   => $leadMedium,
                'campaign' => $leadCampaign,
                'content'  => $leadContent,
            ];
 
        } else {
 
            $ads = [
                'origin'   => 'organic',
                'active'   => 0,
                'medium'   => null,
                'campaign' => null,
                'content'  => null,
            ];
        }
 
        //$this->cookies->delete('ads');
        //setcookie('ads', json_encode($ads), time() + 2592000, '/', '.123i.com.br');
 
        $x = setcookie('ads', json_encode($ads), time() + 2592000, '/', '.123i.uol.com.br');
        // var_dump($x);
        // die();
 
        $this->cookies->set('123i_ads', json_encode($ads), time() + 2592000);
 
        return $ads;
    }
    /**
     * undocumented function
     *
     * @return void
     * @author
     **/
    public function recognizeUrl($params, $validate = true)
    {
        $type = 'offer';
        if ($params['goal'] == 'shipping') {
            $type = 'new';
        }
 
        if ($params['goal'] == 'catalog') {
            $type = 'used';
        }
        if (strstr($_SERVER['REQUEST_URI'], 'lancamentos-comerciais')) {
            $type                    = 'newCommercial';
            $params['is_commercial'] = 1;
        };
        if (strstr($_SERVER['REQUEST_URI'], 'lancamentos-minha-casa-minha-vida')) {
            $type              = 'newMcmv';
            $params['is_mcmv'] = 1;
        };
 
        $page = $this->request->get('p') ? $this->request->get('p') : 1;
        if ($page > 1) {
            $params['page'] = $page;
        }
        $this->verifyRedirect();
 
        $recognizeUrl = RecognizeUrlService::start($type);
        $params       = $recognizeUrl->run($params);
 
        if ($validate) {
            if ($params['isValid'] === false) {
                if (isset($params['currentUrl']) && $params['currentUrl']) {
                    return $this->redirectToUrl($params['currentUrl']);
                }
                $this->set404();
            }
        }
 
        return $params;
    }
 
    /**
     * 404
     * @todo colocar em serviço
     * @return void
     * @author Ariana Kataoka
     **/
    public function set404()
    {
        $response = new \Phalcon\Http\Response();
 
        //Set status code
        $response->setStatusCode(404, 'Not Found');
        $response->setContent("Sorry, the page doesn't exist");
        $response->send();
        $this->view->render('index', 'notFound');
 
        $this->view->finish();
        echo $this->view->getContent();
        die();
    }
 
    /**
     * @todo colocar em serviço
     **/
    protected function set401()
    {
        $response = new \Phalcon\Http\Response();
        $response->setStatusCode(401, 'Unauthorized');
        $response->send();
        die();
    }
 
    /**
     * @todo colocar em serviço
     **/
    protected function setDownloadCsv($content)
    {
        $response = new \Phalcon\Http\Response();
        $response->setHeader("Content-Type", "text/csv");
        $response->setStatusCode(200, 'OK');
        $response->setContent($content);
        $response->send();
        die();
    }
 
    protected function setDownloadTar($content)
    {
        $response = new \Phalcon\Http\Response();
        $response->setHeader("Content-Type", "application/octet-stream");
        $response->setHeader("Content-Description:", "File Transfer");
        $response->setStatusCode(200, 'OK');
        $response->setContent($content);
        $response->send();
        die();
    }
 
    /**
     * Verifica se a url será redirecionada
     *
     * @return void
     * @author Raphael Giovanini
     **/
    public function verifyRedirect()
    {
        $urlActual = $this->request->getUri();
 
        $redirect = false;
 
        if (substr($urlActual, -9) == '/-/-/-/-/') {
            $this->redirectToUrl(str_replace('/-/-/-/-/', '', $urlActual));
        }
        if (substr($urlActual, -8) == '/-/-/-/-') {
            $this->redirectToUrl(str_replace('/-/-/-/-', '', $urlActual));
        }
        if (substr($urlActual, -7) == '/-/-/-/') {
            $this->redirectToUrl(str_replace('/-/-/-/', '', $urlActual));
        }
        if (substr($urlActual, -6) == '/-/-/-') {
            $this->redirectToUrl(str_replace('/-/-/-', '', $urlActual));
        }
        if (substr($urlActual, -5) == '/-/-/') {
            $this->redirectToUrl(str_replace('/-/-/', '', $urlActual));
        }
        if (substr($urlActual, -4) == '/-/-') {
            $this->redirectToUrl(str_replace('/-/-', '', $urlActual));
        }
        if (substr($urlActual, -3) == '/-/') {
            $this->redirectToUrl(str_replace('/-/', '', $urlActual));
        }
        if (substr($urlActual, -2) == '/-') {
            $this->redirectToUrl(str_replace('/-', '', $urlActual));
        }
        if (substr($urlActual, -1) == '/') {
            $this->redirectToUrl(substr($urlActual, 0, strlen($urlActual) - 1));
        }
 
    }
    /**
     * Redirecionar
     *
     * @return void
     * @author Raphael Giovanini
     **/
    public function redirectToUrl($url, $status = 302)
    {
        $response = new \Phalcon\Http\Response();
        $response->redirect($url, true, $status);
        $response->send();
        die();
    }
 
    public function newOrReturn($c = 'returned'){
        if ($this->cookies->has('userUniqueType')) {
            // Get the cookie
            $c = $this->cookies->get('userUniqueType');
        } elseif (isset($_COOKIE['userUniqueType']) && strlen($_COOKIE['userUniqueType']) > 0) {
 
            $c = $_COOKIE['userUniqueType'];
        }
        $this->cookies->set('userUniqueType', (string) $c, time() + 500);
        $this->view->setVar('cookieUserType', (string) $c);  
    }
    /**
     * Setar cookie de navegação para o usuário
     *
     * @return string
     * @author Raphael Giovanini
     **/
    public function cookieUser()
    {
        if ($this->cookies->has('userUnique')) {
            // Get the cookie
            $this->newOrReturn('returned');
            return $this->cookies->get('userUnique');
        } elseif (isset($_COOKIE['userUnique']) && strlen($_COOKIE['userUnique']) > 0) {
            $this->newOrReturn('returned');
            return $_COOKIE['userUnique'];
        } else {
 
            $uuid = sha1(md5(uniqid(rand() + time(), true)));
            $this->cookies->set('userUnique', $uuid, time() + 2592000);
 
            setcookie('userUnique', $uuid, time() + 2592000, '/', '.123i.com.br');
 
            $this->newOrReturn('new');
            return $uuid;
        }
    }
 
    public function cachePage()
    {
        $cacheConfig = ['host' => '123i-mc1.xpg.net.br', 'port' => 11213];
        if (isset($_GET['utm_source']) && count($_POST) == 0) {
            return true;
        }
        if (class_exists('Memcached')) {
            $memcacheObj = new \Memcached();
            $memcacheObj->addServer($cacheConfig['host'], $cacheConfig['port']);
            $result = $memcacheObj->get('page_' . md5($_SERVER['REQUEST_URI']));
 
        } else {
 
            $memcache = new \Memcache;
            $memcache->connect($cacheConfig['host'], $cacheConfig['port']);
            $result = $memcache->get('page_' . md5($_SERVER['REQUEST_URI']));
 
        }
        if ($result) {
            die($result . '<!-- m -->');
        }
 
    }
 
    public function getContent($url, $r = true)
    {
        list($cache, $data, $cacheName) = \Infra\LoadersConfigs\ConfigCache::getCache('cache_model_medium', __METHOD__, func_get_args());
        if ($data) {
            return $data;
        }
 
        $url = str_replace('https', 'http', $url);
        $ch  = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $content = trim(curl_exec($ch));
        if (strlen($content) == 0 && $r) {
            $x = curl_getinfo($ch);
            curl_close($ch);
            if ($x['http_code'] === 302) {
                $content = $this->getContent($x['redirect_url'], false);
            }
        } else {
            curl_close($ch);
        }
 
        if ($content && is_object($cache)) {
            $cache->save($cacheName, $content);
        }
 
        return $content;
    }
    public function getApi($url)
    {
        list($cache, $data, $cacheName) = \Infra\LoadersConfigs\ConfigCache::getCache('cache_model_medium', __METHOD__, func_get_args());
        if ($data) {
            return $data;
        }
        $url = str_replace('https', 'http', $url);
 
        $ch = curl_init();
 
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $content = trim(curl_exec($ch));
 
        curl_close($ch);
 
        $content = json_decode($content, true);
 
        if ($content && is_object($cache)) {
            $cache->save($cacheName, $content);
        }
        return $content;
    }
 
    public function setDefaultPage($folder, $path)
    {
        $this->view->setLayout('map');
        $this->view->setVar('container', true);
        $this->view->setVar('skip_search', true);
 
        $overlay = \SeoDomain\OverlayService::start();
        $this->view->setVar('records', ['overlay' => [
            'column1' => $overlay->column1(),
            'column2' => $overlay->column2(),
            'column3' => $overlay->column3(),
        ],
        ]);
        $this->view->render($folder, $path);
        $this->view->finish();
        echo $this->view->getContent();
        die();
    }
 
    public function isOrganic()
    {
        if (isset($_SERVER['HTTP_REFERER'])) {
            $thereferer = strtolower($_SERVER['HTTP_REFERER']);
            // see if it comes from google
            if (strpos($thereferer, "google")) {
                return true;
            }
        }
        return false;
    }
}
#8Application\Controller\BaseController->initialize()
#9Phalcon\Dispatcher->dispatch()
#10Phalcon\Mvc\Application->handle()
<?php
 
 
namespace Core\Mvc;
 
use Phalcon\Mvc\Application as MvcApplication,
    Phalcon\Events\Manager as EventsManager,
    Phalcon\Mvc\Dispatcher,
    Phalcon\Mvc\View,
    Phalcon\DI\FactoryDefault as DiFactory,
    Phalcon\Http\Response,
    Phalcon\Config,
    Phalcon\Debug,
    Exception;
 
class Application extends MvcApplication
{
    /**
     * @var boolean
     */
    protected static $debugMode = false;
 
    /**
     * @var array
     */
    protected $defaultBootstrapListeners = [
        // bootstrap:init
        'Core\Bootstrap\RegisterModulesPathsListener',
        'Core\Bootstrap\RegisterModulesListener',
        'Core\Bootstrap\LoadModulesListener',
 
        // bootstrap:beforeMergeConfig
        'Core\Bootstrap\RegisterViewStrategyListener',
 
        // Database
        'Core\Bootstrap\RegisterDatabaseListener',
 
        // bootstrap:mergeConfig
        'Core\Bootstrap\ConfigCacheListener',
        'Core\Bootstrap\MergeGlobConfigListener',
        'Core\Bootstrap\MergeModulesConfigListener',
 
        // bootstrap:afterMergeConfig
        'Core\Bootstrap\RegisterDIListener',
        'Core\Bootstrap\RegisterRoutesListener',
        'Core\Bootstrap\RegisterViewHelpersListener',
 
        // bootstrap:bootstrapModules
        'Core\Bootstrap\BootstrapModulesListener',
    ];
 
    /**
     * @param boolean $flag
     * @return void
     */
    public static function setDebugMode($flag = true)
    {
        $reportingLevel = $flag ? E_ALL | E_STRICT : 0;
        error_reporting($reportingLevel);
 
        static::$debugMode = (bool) $flag;
    }
 
    /**
     * @return boolean
     */
    public static function isDebugMode()
    {
        return static::$debugMode;
    }
 
    /**
     * @param array $configuration
     * @return Core\Mvc\Application
     */
    public static function init($configuration = [])
    {
        static $application;
 
        if ($application instanceof Application) {
            return $application;
        }
 
        Application::setDebugMode(Application::isDebugMode());
 
        $config = new Config($configuration);
        $di = new DiFactory();
        $di->setShared('config', $config);
 
        $application = new Application();
        $application->setDI($di);
 
        $eventsManager = $di->getShared('eventsManager');
        $application->setEventsManager($eventsManager);
 
        $dispatcher = new Dispatcher();
        $dispatcher->setEventsManager($eventsManager);
        $di->setShared('dispatcher', $dispatcher);
 
        $view = new View();
 
        // verifiyng if volt is enabled
        if (isset($config['volt']) && $config['volt']) {
            $view->registerEngines([
              '.phtml' => 'volt'
            ]);
        }
 
        $di->setShared('view', $view);
 
        $di->set(
            'dispatcher',
            function () use ($di) {
                $eventsManager = $di->getShared('eventsManager');
                $eventsManager->attach(
                    'dispatch:beforeException',
                    function ($event, $dispatcher, $exception) {
                        switch ($exception->getCode()) {
                            case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                            case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                                $dispatcher->forward(
                                    [
                                        'module' => 'Application',
                                        'namespace' => 'Application\Controller',
                                        'controller' => 'index',
                                        'action' => 'notFound',
                                    ]
                                );
                                return false;
                                break; // for checkstyle
                            default:
                                $dispatcher->forward(
                                    [
                                        'module' => 'Application',
                                        'namespace' => 'Application\Controller',
                                        'controller' => 'index',
                                        'action' => 'uncaughtException',
                                    ]
                                );
                                return false;
                                break; // for checkstyle
                        }
                    }
                );
                $dispatcher = new Dispatcher();
                $dispatcher->setEventsManager($eventsManager);
                return $dispatcher;
            },
            true
        );
 
        return $application->bootstrap();
    }
 
    /**
     * @return Core\Mvc\Application
     */
    public function bootstrap()
    {
        $eventsManager = $this->getEventsManager();
 
        foreach ($this->defaultBootstrapListeners as $listener) {
            $listener = new $listener();
            $eventsManager->attach('bootstrap', $listener);
        }
 
        return $this;
    }
 
    /**
     * @param string $url optional
     * @return Phalcon\Http\ResponseInterface
     */
    public function handle($url = '')
    {
        try {
            $eventsManager = $this->getEventsManager();
            $eventsManager->fire('bootstrap:init', $this);
            $eventsManager->fire('bootstrap:beforeMergeConfig', $this);
            $eventsManager->fire('bootstrap:mergeConfig', $this);
            $eventsManager->fire('bootstrap:afterMergeConfig', $this);
            $eventsManager->fire('bootstrap:bootstrapModules', $this);
            $eventsManager->fire('bootstrap:beforeHandle', $this);
            return parent::handle($url);
        } catch (Exception $e) {
 
            if (Application::isDebugMode()) {
                (new Debug())->onUncaughtException($e);
            }
            return new Response();
        }
    }
}
#11Core\Mvc\Application->handle()
<?php
ini_set('display_errors', 0);
function convert($size)
{
    $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
    return $size > 0 ? @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i] : false;
}
 
function pr($variable)
{
    echo '<pre>';
    print_r($variable);
    echo '</pre>';
}
 
// echo convert(memory_get_usage(true)); // 123 kb
 
if (version_compare(PHP_VERSION, '5.4.0', '<=')) {
    exit(sprintf(
        'To run this application required PHP >= 5.4.0 Current version is %s.',
        PHP_VERSION
    ));
}
if (!extension_loaded('phalcon')) {
    exit('Phalcon extension is not installed. See http://phalconphp.com/en/download');
}
 
// \Phalcon\Version::get();
 
chdir(dirname(__DIR__));
require 'init_autoloader.php';
 
// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) {
    return false;
}
 
use Core\Mvc\Application;
 
Application::setDebugMode(true);
 
$application = Application::init(require './config/application.config.php');
 
$di = $application->getDi();
 
//adicionando configuracoes infra
use \Infra\RegisterListeners\RegisterListeners;
RegisterListeners::init($di);
 
 
//
if ($di->get('debug_www2')) {
    echo $application->handle()->getContent();
}else{
 
    $nginx_cache_time = 15 * 60;
 
    $htmlOutput = $application->handle()->getContent() ;//str_replace(["\n","\r","  "],"", trim($application->handle()->getContent()));
 
    // if (count($_POST)==0 && !isset($_GET['utm_source'])) {
    //     if(class_exists('Memcached')){
    //         $memcacheObj = new Memcached();
    //         $memcacheObj->addServer('localhost', 11211);
    //         $memcacheObj->set('page_'.md5($_SERVER['REQUEST_URI']), $htmlOutput, $nginx_cache_time);
    //     }else{
    //         $memcache = new Memcache;
    //         $memcache->connect('localhost', 11211);
    //         $memcache->set('page_'.md5($_SERVER['REQUEST_URI']), $htmlOutput, 0, $nginx_cache_time);
    //     }
    // }
 
    echo $htmlOutput;
}
KeyValue
_url/imoveis-venda/sp/rio-claro/-/jardim-residencial-copacabana/apartamento
KeyValue
USER123i
HOME/home/123i
FCGI_ROLERESPONDER
QUERY_STRING_url=/imoveis-venda/sp/rio-claro/-/jardim-residencial-copacabana/apartamento
REQUEST_METHODGET
CONTENT_TYPE
CONTENT_LENGTH
SCRIPT_FILENAME/home/123i/website/userinterface/www/public/index.php
SCRIPT_NAME/index.php
PATH_INFO
PATH_TRANSLATED/home/123i/website/userinterface/www/public
REQUEST_URI/imoveis-venda/sp/rio-claro/-/jardim-residencial-copacabana/apartamento?
DOCUMENT_URI/index.php
DOCUMENT_ROOT/home/123i/website/userinterface/www/public
SERVER_PROTOCOLHTTP/1.0
GATEWAY_INTERFACECGI/1.1
SERVER_SOFTWAREnginx/1.8.0
REMOTE_ADDR187.17.123.194
REMOTE_PORT17200
SERVER_ADDR187.17.123.83
SERVER_PORT80
SERVER_NAMEwww2.123i.com.br
REDIRECT_STATUS200
HTTP_HOSTwww2.123i.com.br
HTTP_X_REAL_IP200.147.35.67
HTTP_AMBIENTE123i.uol.com.br
HTTP_CONNECTIONclose
HTTP_X_FORWARDED_PORT443
HTTP_X_FORWARDED_PROTOhttps
HTTP_USER_AGENTCCBot/2.0 (https://commoncrawl.org/faq/)
HTTP_ACCEPTtext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_X_FORWARDED_FOR34.204.11.236, 200.147.15.64
HTTP_COOKIE
HTTP_X_VARNISH1714564202
HTTP_ACCEPT_ENCODINGgzip
PHP_SELF/index.php
REQUEST_TIME_FLOAT1545141230.24
REQUEST_TIME1545141230
argvArray([0] => _url=/imoveis-venda/sp/rio-claro/-/jardim-residencial-copacabana/apartamento)
argc1
#Path
0/home/123i/website/userinterface/www/public/index.php
1/home/123i/website/userinterface/www/init_autoloader.php
2/home/123i/website/userinterface/www/vendor/Core/Mvc/Application.php
3/home/123i/website/userinterface/www/config/application.config.php
4/home/123i/website/userinterface/www/vendor/Core/Bootstrap/RegisterModulesPathsListener.php
5/home/123i/website/userinterface/www/vendor/Core/Bootstrap/RegisterModulesListener.php
6/home/123i/website/userinterface/www/vendor/Core/Bootstrap/LoadModulesListener.php
7/home/123i/website/userinterface/www/vendor/Core/Bootstrap/RegisterViewStrategyListener.php
8/home/123i/website/userinterface/www/vendor/Core/Bootstrap/RegisterDatabaseListener.php
9/home/123i/website/userinterface/www/vendor/Core/Bootstrap/ConfigCacheListener.php
10/home/123i/website/userinterface/www/vendor/Core/Bootstrap/MergeGlobConfigListener.php
11/home/123i/website/userinterface/www/vendor/Core/Bootstrap/MergeModulesConfigListener.php
12/home/123i/website/userinterface/www/vendor/Core/Bootstrap/RegisterDIListener.php
13/home/123i/website/userinterface/www/vendor/Core/Bootstrap/RegisterRoutesListener.php
14/home/123i/website/userinterface/www/vendor/Core/Bootstrap/RegisterViewHelpersListener.php
15/home/123i/website/userinterface/www/vendor/Core/Bootstrap/BootstrapModulesListener.php
16/home/123i/website/infra/RegisterListeners/RegisterListeners.php
17/home/123i/website/infra/RegisterListeners/RegisterDebugListener.php
18/home/123i/website/infra/config/debug.global.php
19/home/123i/website/infra/RegisterListeners/RegisterDatabaseListener.php
20/home/123i/website/infra/config/databases.global.php
21/home/123i/website/infra/RegisterListeners/RegisterMailListener.php
22/home/123i/website/infra/config/mail.global.php
23/home/123i/website/infra/RegisterListeners/RegisterGearmanListener.php
24/home/123i/website/infra/config/gearman.global.php
25/home/123i/website/infra/RegisterListeners/RegisterCdnListener.php
26/home/123i/website/infra/config/cdn.global.php
27/home/123i/website/infra/RegisterListeners/RegisterCacheListener.php
28/home/123i/website/infra/config/cache.global.php
29/home/123i/website/infra/RegisterListeners/RegisterSessionListener.php
30/home/123i/website/infra/config/session.global.php
31/home/123i/website/infra/RegisterListeners/RegisterBaseUrlListener.php
32/home/123i/website/infra/config/base_url.global.php
33/home/123i/website/infra/RegisterListeners/RegisterGitListener.php
34/home/123i/website/infra/config/git.php
35/home/123i/website/infra/RegisterListeners/RegisterImagesListener.php
36/home/123i/website/infra/config/images.php
37/home/123i/website/infra/RegisterListeners/RegisterExternalServiceListener.php
38/home/123i/website/infra/config/external_service.global.php
39/home/123i/website/infra/RegisterListeners/RegisterSolrListener.php
40/home/123i/website/vendor/autoload.php
41/home/123i/website/vendor/composer/autoload_real.php
42/home/123i/website/vendor/composer/ClassLoader.php
43/home/123i/website/vendor/composer/include_paths.php
44/home/123i/website/vendor/composer/autoload_namespaces.php
45/home/123i/website/vendor/composer/autoload_psr4.php
46/home/123i/website/vendor/composer/autoload_classmap.php
47/home/123i/website/vendor/composer/autoload_files.php
48/home/123i/website/vendor/react/promise/src/functions_include.php
49/home/123i/website/vendor/react/promise/src/functions.php
50/home/123i/website/vendor/facebook/php-sdk-v4/src/Facebook/polyfills.php
51/home/123i/website/infra/config/solr.global.php
52/home/123i/website/userinterface/www/module/Application/Module.php
53/home/123i/website/userinterface/www/module/Catalog/Module.php
54/home/123i/website/userinterface/www/module/Offer/Module.php
55/home/123i/website/userinterface/www/vendor/Core/Mvc/DefaultViewStrategy.php
56/home/123i/website/userinterface/www/config/autoload/ads.global.php
57/home/123i/website/userinterface/www/module/Offer/src/Controller/IndexController.php
58/home/123i/website/userinterface/www/module/Application/src/Controller/BaseController.php
Memory
Usage2097152