Phalcon Framework 3.4.2

PDOException: SQLSTATE[08004] [1040] Too many connections

/home/finduslocal/public_html/config/services.php (176)
#0PDO->__construct(mysql:host=10.11.1.20;port=3308;dbname=findus_prod2;charset=utf8, findus_prod, URr=zyaZubbKYll>B>FaxYhNx, Array([3] => 2))
#1Phalcon\Db\Adapter\Pdo->connect(Array([host] => 10.11.1.20, [username] => findus_prod, [port] => 3308, [password] => URr=zyaZubbKYll>B>FaxYhNx, [dbname] => findus_prod2, [charset] => utf8, [options] => Array()))
#2Phalcon\Db\Adapter\Pdo->__construct(Array([host] => 10.11.1.20, [username] => findus_prod, [port] => 3308, [password] => URr=zyaZubbKYll>B>FaxYhNx, [dbname] => findus_prod2, [charset] => utf8, [options] => Array()))
/home/finduslocal/public_html/config/services.php (176)
<?php
/**
 * Created by Novnik Ltd.
 * User: artdevue - services.php
 * Date: 25.02.17
 * Time: 15:39
 * Project: phalcon-blank
 */
 
/**
 * Services are globally registered in this file
 */
 
use Phalcon\Cache\Backend\File;
use Phalcon\Cache\Frontend\Output;
use Phalcon\Mvc\Router,
    Phalcon\Mvc\Router\Group as RouterGroup,
    Phalcon\Mvc\Url as UrlResolver,
    Phalcon\DI\FactoryDefault,
    Phalcon\Mvc\View,
    Phalcon\Security,
    Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter,
    Phalcon\Flash\Direct as Flash,
    Phalcon\Crypt,
    Phalcon\Mvc\View\Engine\Volt,
    Phalcon\Mvc\Model\Metadata\Files as MetaDataAdapter,
    Phalcon\Session\Adapter\Files as SessionAdapter;
use Phalcon\Mvc\Router\Annotations as RouterAnnotations;
 
/**
 * The FactoryDefault Dependency Injector automatically register
 * the right services providing a full stack framework
 */
$di = new FactoryDefault();
 
/**
 * Registering a router
 */
$di['router'] = function () use ($config)
{
 
    //$router = new Router(false);
    // Use the annotations router. We're passing false as we don't want the router to add its default patterns
    $router = new RouterAnnotations(false);
 
//    $router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI);
    $router->removeExtraSlashes(true);
 
    if (!$config->debug)
    {
        $router->setDefaultModule($config->default_module);
        $router->setDefaults(['controller' => 'index', 'action' => 'route404']);
    }
 
    // Get explode uri
    $url_array = explode("/", $_SERVER['REQUEST_URI']);
    $module    = $config->default_module;
 
    $_SERVER['REQUEST_URI'] = str_replace("///","/",$_SERVER['REQUEST_URI']);
    $_SERVER['REQUEST_URI'] = str_replace("//","/",$_SERVER['REQUEST_URI']);
 
    $prefix_lang = '';
    $config->lang_active = $config->default_lang;
 
    // If multilanguage is allowed
    if ($config->multilang)
    {
        $langkey             =
            strlen($_SERVER['REQUEST_URI']) == 2 ? $_SERVER['REQUEST_URI'] : substr($_SERVER['REQUEST_URI'], 1, 2);
 
        if (in_array($langkey, array_keys($config->languages->toArray())) && $langkey != $config->default_lang)
        {
            $prefix_lang         = '/' . $langkey;
            $config->lang_active = $langkey;
        }
    }
 
    // Connecting routes for modules
    foreach ($config->modules as $key => $modul)
    {
        if (file_exists($modul->dir . 'config/routes.php'))
        {
            // Create a group with a backend module and controller
            $route = new RouterGroup([
                "module" => $key
            ]);
 
            // All the routes start with $prefix_router
            if (!empty($modul->prefix_router))
            {
                $route->setPrefix($prefix_lang . "/" . $modul->prefix_router);
                //$route->setPrefix("/" . $modul->prefix_router);
            } else
            {
                if (strlen($prefix_lang) > 1)
                {
                    $route->setPrefix($prefix_lang);
                }
 
            }
 
            // Hostname restriction
            if (!empty($modul->host_name))
            {
                $route->setHostName($modul->host_name);
            }
 
            $home_slesh = '';
 
            if ($key == $config->default_module && $_SERVER['REQUEST_URI'] == '/' )
            {
                $home_slesh = '/';
            }
 
            require $modul->dir . 'config/routes.php';
 
            // Add the group to the router
            $router->mount($route);
        }
 
        if (count($url_array) >= 2 && $url_array[1] == $modul->prefix_router)
        {
            $module = $key;
        }
    }
 
    if (!$config->debug)
    {
        $router->notFound([
            "module"     => $module,
            "controller" => "base",
            "action"     => "route404"
        ]);
    }
 
    return $router;
};
$di->set('cookies', function () {
    $cookies = new Phalcon\Http\Response\Cookies();
    $cookies->useEncryption(false);
    return $cookies;
}, true);
 
/**
 * Register the global configuration as config
 */
$di->set('config', $config);
 
/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->set('url', function () use ($config)
{
    $url = new UrlResolver();
    $url->setBaseUri('/');  // here
    return $url;
});
 
/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->set('Entrust', function () use ($config)
{
    return new Library\Entrust\Entrust();
});
 
//$di->set('eventsManager', 'Phalcon\Events\Manager', true);
$di->set('assets', 'Phalcon\Assets\Manager', true);
 
/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di['db'] = function () use ($config)
{
    return new DbAdapter([
        'host'     => $config->database->host,
        'username' => $config->database->username,
        'port' => $config->database->port,
        'password' => $config->database->password,
        'dbname'   => $config->database->dbname,
        'charset'  => $config->database->charset,
        'options' => [
            #PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
            #PDO::ATTR_PERSISTENT => true
//            1002 => "SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))"
        ]
    ]);
};
$di->set(
    'dispatcher',
    function () {
        // Create an event manager
        $eventsManager = new \Phalcon\Events\Manager();
 
        // Attach a listener for type 'dispatch'
        $eventsManager->attach(
            'dispatch',
            function (\Phalcon\Events\Event $event, $dispatcher) {
            }
        );
 
        $dispatcher = new \Phalcon\Mvc\Dispatcher();
 
        // Bind the eventsManager to the view component
        $dispatcher->setEventsManager($eventsManager);
 
        return $dispatcher;
    },
    true
);
/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di['modelsMetadata'] = function () use ($config)
{
    return new MetaDataAdapter([
        'metaDataDir' => $config->application->cacheDir . 'metaData/'
    ]);
};
 
/**
 * Crypt service
 */
$di->set('crypt', function () use ($config)
{
    $crypt = new \Phalcon\Crypt();
    $crypt->setKey($config->application->cryptSalt);
 
    return $crypt;
});
 
/**
 * Start the session the first time some component request the session service
 */
$di->set('session', function () use ($config)
{
    $session = new SessionAdapter([
        'uniqueId' => $config->prefix_session
    ]);
    $session->start();
 
    return $session;
});
 
/**
 * Flash service with custom CSS classes
 */
$di->set('flash', function ()
{
    return new Flash([
        'error'   => 'alert alert-danger notification-error',
        'success' => 'alert alert-success',
        'notice'  => 'alert alert-info',
        'warning' => 'alert alert-warning',
    ]);
});
 
$di->set(
    "flashSession",
    function () {
        return new Phalcon\Flash\Session([
            'error'   => 'alert alert-danger notification-error',
            'success' => 'alert alert-success',
            'notice'  => 'alert alert-info',
            'warning' => 'alert alert-warning',
        ]);
    }
);
 
/**
 * This component aids the developer in common security tasks such as password
 * hashing and Cross-Site Request Forgery protection (CSRF).
 */
$di->set('security', function ()
{
    $security = new Security();
 
    //Set the password hashing factor to 12 rounds
    $security->setWorkFactor(12);
 
    return $security;
}, true);
 
/**
 * Registering a Auth component
 */
$di->setShared('auth', '\Library\Auth\Auth');
$di->setShared('slug', '\Library\Slug\Slug');
$di->setShared('tag', '\Library\Tag');
/**
 * Register View
 */
$di['view'] = function () use ($config)
{
 
    $view = new View();
    $view->setViewsDir($config->application->viewsDir);
 
    $view->registerEngines([
        '.volt'  => function ($view, $di) use ($config)
        {
 
            $volt = new Volt($view, $di);
 
            $volt->setOptions([
                'compiledPath'      => $config->application->cacheDir . 'volt/',
                'compiledSeparator' => '_'
            ]);
 
            return $volt;
        },
        '.phtml' => 'Phalcon\Mvc\View\Engine\Php',
        '.php'   => 'Phalcon\Mvc\View\Engine\Php'
    ]);
 
    return $view;
};
/**
 * View cache
 */
//$di['viewCache'] = function ()
//{
//
//    //Cache data for one day by default
//    $frontCache = new Output([
//        "lifetime" => 2592000
//    ]);
//
//    /*return new \Phalcon\Cache\Backend\Apc($frontCache, array(
//        "prefix" => "cache-"
//    ));*/
//
//    return new File($frontCache, [
//        "cacheDir" => PROJECT_PATH . "cache/views/",
//        "prefix"   => "cache-"
//    ]);
//};
 
/**
 *  Setup mail system
 */
$di->set('mail', function ()
{
    $mail_setting    = include PROJECT_PATH . 'config/mail.php';
    $mail            = new \PHPMailer\PHPMailer\PHPMailer(true);
    $mail->SMTPDebug = $mail_setting->get('SMTPDebug');   // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host       = $mail_setting->get('Host');       // Specify main and backup SMTP servers
    $mail->SMTPAuth   = $mail_setting->get('SMTPAuth');   // Enable SMTP authentication
    $mail->Username   = $mail_setting->get('Username');   // SMTP username
    $mail->Password   = $mail_setting->get('Password');   // SMTP password
    $mail->SMTPSecure = $mail_setting->get('SMTPSecure'); // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = $mail_setting->get('Port');
    $mail->setFrom($mail_setting->setFrom->get('email'), $mail_setting->setFrom->get('name'));
 
    return $mail;
});
 
/**
 * Register Helpers Service
 */
if (!$di->has('helpers'))
{
    $di->setShared('helpers', 'Library\Helpers');
}
if (!$di->has('carbon'))
{
    $di->set('carbon', function () use ($config)
    {
        return new \Carbon\Carbon();
    });
}
if (!$di->has('e'))
{
    $di->set('e', function () use ($config)
    {
        return new \Phalcon\Escaper();
    });
}
if (!$di->has('random'))
{
    $di->set('random', function () use ($config)
    {
        return new \Phalcon\Security\Random();
    });
}
if (!$di->has('parse_rss'))
{
    $di->set('parse_rss', function () use ($config)
    {
        return new \Novnik\ParseRss\ParseRss([
            'file_log' => 'Runtime/parse-rss.log',
            'timezone' => 'US/Eastern'
        ]);
    });
}
if (!$di->has('sitemapCache'))
{
    $di->set('sitemapCache', function () use ($config)
    {
        //Cache data for one day by default
        $frontCache = new Phalcon\Cache\Frontend\Output(["lifetime" => 2592000]);
 
        //Memcached connection settings
        return new Phalcon\Cache\Backend\File($frontCache, [
            "cacheDir" => "../cache/sitemap/",
            "prefix"   => ""
        ]);
    });
}
 
/**
 * Register Translation Service
 */
if (!$di->has('trans'))
{
    $di->setShared('trans', function ()
    {
        $trans = new \Library\Trans();
 
        return $trans->get();
    });
}
/**
 * Register Other
 */
if (!$di->has('trans'))
{
    $di->setShared('trans', function ()
    {
//        $trans = new \Library\Trans();
//
//        return $trans->get();
    });
}
 
// Register Subscription
/**
 * Registering a Codes library
 */
$di->setShared('codes', 'Library\Codes');
 
// Models cache service Register
$di->set('modelsCache', function ()
{
    // By default, the cache data is stored one day
    $frontCache = new \Phalcon\Cache\Frontend\Data([
        "lifetime" => 86400
    ]);
 
    return new File($frontCache, [
        "cacheDir" => PROJECT_PATH . "cache/model/",
        "prefix"   => "cache-"
    ]);
});
 
$di->set('userCache', function ()
{
    $frontCache = new \Phalcon\Cache\Frontend\Output([
        "lifetime" => 86400
    ]);
 
    return new File($frontCache, [
        "cacheDir" => PROJECT_PATH . "cache/model/",
        "prefix" => "user-"
    ]);
});
 
 
if (!$di->has('imailapi'))
{
    $di->setShared('imailapi', 'Library\ImailApi\ImailApi');
}
 
if (!$di->has('appAuth'))
{
    $di->setShared('appAuth', '\App\Auth\Auth');
}
 
if (!$di->has('locationServices'))
{
    $di->setShared('locationServices', '\App\Service\LocationServices');
}
 
/**
 * Register PHP Time Ago
 */
if (!$di->has('timeAgo'))
{
    $di->setShared('timeAgo', 'Westsworld\TimeAgo');
 
    /*$di->setShared('timeAgo', function ()
    {
        return new \Westsworld\TimeAgo();
    });*/
}
#3Closure->{closure}()
#4Phalcon\Di\Service->resolve(null, Object(Phalcon\Di\FactoryDefault))
#5Phalcon\Di->get(db, null)
#6Phalcon\Di->getShared(db)
#7Phalcon\Mvc\Model\Manager->_getConnection(Object(Apps\Commons\Models\Users: 58), null)
#8Phalcon\Mvc\Model\Manager->getReadConnection(Object(Apps\Commons\Models\Users: 58))
#9Phalcon\Mvc\Model->getReadConnection()
#10Phalcon\Mvc\Model\Query->getReadConnection(Object(Apps\Commons\Models\Users: 58), Array([models] => Array([0] => Apps\Commons\Models\Users), [tables] => Array([0] => users), [columns] => Array([apps\Commons\Models\Users] => Array([type] => object, [model] => Apps\Commons\Models\Users, [column] => users, [balias] => apps\Commons\Models\Users)), [limit] => Array([number] => Array([type] => placeholder, [value] => :APL0))), Array([APL0] => 1), Array([APL0] => 1))
#11Phalcon\Mvc\Model\Query->_executeSelect(Array([models] => Array([0] => Apps\Commons\Models\Users), [tables] => Array([0] => users), [columns] => Array([apps\Commons\Models\Users] => Array([type] => object, [model] => Apps\Commons\Models\Users, [column] => users, [balias] => apps\Commons\Models\Users)), [limit] => Array([number] => Array([type] => placeholder, [value] => :APL0))), Array([APL0] => 1), Array([APL0] => 1))
#12Phalcon\Mvc\Model\Query->execute()
#13Phalcon\Mvc\Model::findFirst(null)
/home/finduslocal/public_html/library/Auth/Auth.php (329)
<?php namespace App\Auth;
 
/**
 * Created by PhpStorm.
 * User: AtrDevue - Auth.php
 * Date: 20.07.16
 * Time: 13:54
 * Project: novnikv2
 */
 
use Apps\Commons\Models\RememberTokens;
use Apps\Commons\Models\SuccessLogins;
use Apps\Commons\Models\Users;
use Phalcon\Mvc\User\Component,
    Phalcon\Exception;
 
/**
 * App\Auth\Auth
 *
 * Manages Authentication/Identity Management in Novnikv2
 */
class Auth extends Component
{
    /**
     * @var Users
     */
    protected $user;
 
    /**
     * Checks the user credentials
     *
     * @param      $email
     * @param      $password
     * @param bool $remember
     * @param      $client_type
     *
     * @return bool|string
     */
    public function check($email, $password, $remember = false)
    {
        // Check user on the basis of
        $user = Users::findFirstByEmail($email);
 
        // Check the user
        if (!$user)
        {
            throw new Exception('No user in the system');
        }
 
        // Check the correct password
        if (!$this->security->checkHash($password, $user->password))
        {
            throw new Exception('You entered the wrong password');
        }
 
        // Check if the user was flagged
        $this->checkUserFlags($user);
 
        // Register the successful login
        $this->saveSuccessLogin($user);
 
        // Check if the remember me was selected
        if ($remember)
        {
            $this->createRememberEnviroment($user);
        }
 
        $this->session->set('auth-identity', [
            'id' => $user->id,
            'name' => $user->getFullName()
        ]);
 
        return true;
    }
 
    /**
     * @param      $username
     * @param      $password
     * @param      $client_type
     * @param bool $remember
     *
     * @return bool
     * @throws Exception
     */
    public function checkUsername($username, $password, $client_type, $remember = false)
    {
        // Finds whether a variable is an array
        if (!is_array($client_type))
        {
            $client_type = [$client_type];
        }
 
        // Check user on the basis of
        $user = Users::findFirst([
            'conditions' => 'username = :username: AND client_type IN ({clientType:array})',
            'bind' => [
                'username' => $username,
                'clientType' => $client_type,
            ]
        ]);
 
        // Check the correct password
        if (!$user || !$this->security->checkHash($password, $user->password))
        {
            throw new Exception('No user in the system or the correct password');
        }
 
        // Check if the user was flagged
        $this->checkUserFlags($user);
 
        // Register the successful login
        $this->saveSuccessLogin($user);
 
        // Check if the remember me was selected
        if ($remember)
        {
            $this->createRememberEnviroment($user);
        }
 
        $this->session->set('auth-identity', [
            'id' => $user->id,
            'name' => $user->getFullName()
        ]);
 
        return true;
    }
 
    /**
     * Checks if the user is banned/inactive
     *
     * @param Users $user
     *
     * @throws bool|string
     */
    public function checkUserFlags(Users $user)
    {
        if ($user->status <> 0)
        {
            throw new Exception('The user is inactive');
        }
 
        if ($user->banned <> 0)
        {
            throw new Exception('Your account has been suspended by administration');
        }
    }
 
    /**
     * Returns the current identity
     *
     * @return array
     */
    public function getIdentity()
    {
        return $this->session->get('auth-identity');
    }
 
    /**
     * Returns the current identity
     *
     * @return string
     */
    public function getName()
    {
        $identity = $this->session->get('auth-identity');
 
        return $identity['name'];
    }
 
    /**
     * Creates the remember me environment settings the related cookies and generating tokens
     *
     * @param Users $user
     *
     * @return bool
     * @throws Exception
     */
    public function saveSuccessLogin($user)
    {
        //return true;
 
        $successLogin = new SuccessLogins();
        $successLogin->usersId = $user->id;
        $successLogin->time = time();
        $successLogin->ipAddress = $this->request->getClientAddress();
        $successLogin->userAgent = $this->request->getUserAgent();
        if (!$successLogin->save())
        {
            $messages = $successLogin->getMessages();
            throw new Exception($messages[0]);
        }
    }
 
    /**
     * Creates the remember me environment settings the related cookies and generating tokens
     *
     * @param Users $user
     *
     * @throws \Exception
     * @return null|void
     */
    public function createRememberEnviroment(Users $user)
    {
        $token = $this->getToken($user);
 
        $remember = RememberTokens::findFirst([
            'token = :token:',
            'bind' => [
                'token' => $token,
            ]
        ]);
 
        if (!$remember)
        {
            $remember = new RememberTokens();
            $remember->usersId = $user->id;
            $remember->token = $token;
            $remember->userAgent = $this->request->getUserAgent();
            if (!$remember->save())
            {
                throw new \Exception;
            }
        }
 
        if (!$remember)
        {
            return null;
        }
 
        $expire = time() + 86400 * 8;
        $this->cookies->set('user', $user->id, $expire, '/', null, null, true);
        $this->cookies->set('token', $token, $expire, '/', null, null, true);
    }
 
    /**
     * Check if the session has a remember me cookie
     *
     * @return boolean
     */
    public function hasRememberMe()
    {
        return $this->cookies->has('user');
    }
 
    /**
     * Generates a pseudo random token key to be used as input’s name in a CSRF check
     *
     * @param Users $user
     *
     * @return string
     */
    protected function getToken(Users $user)
    {
        $userAgent = $this->request->getUserAgent();
        $token = md5($user->email . $userAgent);
 
        return $token;
    }
 
    /**
     * Auths the user by his/her id
     *
     * @param int        $id
     * @param bool|false $remember
     *
     * @return bool
     * @throws Exception
     * @throws \Exception
     */
    public function authUserById($id, $remember = false)
    {
        $user = Users::findFirst($id);
        if ($user == false)
        {
            throw new Exception('The user does not exist');
        }
 
        $this->checkUserFlags($user);
 
        $this->saveSuccessLogin($user);
 
        if ($remember)
        {
            $this->createRememberEnviroment($user);
        }
 
        $this->session->set('auth-identity', [
            'id' => $user->id,
            'name' => $user->getFullName()
        ]);
 
        return true;
    }
 
    /**
     * Logs on using the information in the coookies
     *
     * @return Users|bool
     * @throws Exception
     */
    public function getUser()
    {
//        if (null !== $this->user)
//        {
//            return $this->user;
//        }
 
        /**
         * @var Users $user
         */
 
        $identity = $this->session->get('auth-identity');
//        $identity['id'] = 139280;
        if (is_array($identity) and isset($identity['id']))
        {
            if (!$user = Users::findFirst($identity['id']))
            {
                throw new Exception('The user does not exist');
            }
 
            $this->user = $user;
 
            return $user;
        }
 
        $userId = $this->cookies->get('user')->getValue('int');
        $cookieToken = $this->cookies->get('token')->getValue();
 
        if ($user = Users::findFirst($userId))
        {
            $token = $this->getToken($user);
 
            if ($cookieToken == $token)
            {
                $remember = RememberTokens::findFirst([
                    'usersId = ?0 AND token = ?1',
                    'bind' => [$user->id, $token]
                ]);
 
                if ($remember)
                {
                    //Check if the cookie has not expired
                    if ((time() - (86400 * 8)) < $remember->createdAt)
                    {
                        //Check if the user was flagged
                        $this->checkUserFlags($user);
 
                        //Register identity
                        $this->session->set('auth-identity', [
                            'id' => $user->id,
                            'name' => $user->getFullName()
                        ]);
 
                        //Register the successful login
                        $this->saveSuccessLogin($user);
 
                        $this->user = $user;
 
                        return $user;
                    }
                }
            }
        }
 
        $this->removeCookie();
 
        return false;
    }
 
    /**
     * Removes the user identity information from session
     */
    public function remove()
    {
        if ($this->user)
        {
            $userAgent = $this->request->getUserAgent();
            $token = md5($this->user->email . $userAgent);
 
            $remember = RememberTokens::findFirst([
                'token = ?0',
                'bind' => [$token]
            ]);
 
            if ($remember)
            {
                $remember->delete();
            }
        }
 
        $this->removeCookie();
 
        $this->session->remove('auth-identity');
    }
 
    /**
     * Check if a cookie is defined in the bag or exists in the _COOKIE superglobal
     */
    protected function removeCookie()
    {
        $this->cookies->get('user')->delete();
        $this->cookies->get('token')->delete();
    }
}
#14App\Auth\Auth->getUser()
/home/finduslocal/public_html/apps/frontend/controllers/BaseController.php (51)
<?php
namespace  Apps\Frontend\Controllers;
 
use Apps\Commons\Models\GeodataGeocity;
use Library\Tag;
use Phalcon\Dispatcher;
use Phalcon\Events\Event;
use Phalcon\Mvc\Controller;
 
 
class BaseController extends Controller
{
    /**
     * @var object $geocity
     */
    public $geocity;
 
    /**
     * @var string $local_header_name
     */
    public $local_header_name;
 
    /**
     * Model User
     *
     * @var object $user
     */
    public $user;
 
    /**
     * @var int $user_id
     */
    public $user_id = 0;
 
    /**
     * Triggered before executing the controller/action method. At this point the dispatcher has been initialized
     * the controller and know if the action exist.
     *
     * @param Dispatcher $dispatcher
     *
     * @Triggered on Listeners/Controllers
     */
    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
        $this->view->setPartialsDir(PROJECT_PATH. 'apps/commons/views/');
        $this->view->setLayoutsDir(PROJECT_PATH. 'apps/frontend/views/');
 
        $this->response->setHeader("X-Frame-Options", "DENY");
 
        // This is executed before every found action
        $this->user = $this->appAuth->getUser();
 
        if (!empty($this->user))
        {
            $this->user_id = $this->user->id;
        }
 
        $ip = $this->request->getClientAddress();
 
        $userLocation = $this->locationServices->getIpLocation($ip);
 
        $city    = $this->config->default->get('city');
        $country = $this->config->default->get('country');
 
        if($this->request->has('loccity') || $this->session->has('location')){
 
            if($this->request->has('loccity')){
                $this->session->remove("location");
                $searchByCity = $this->request->get('loccity');
            }else{
                $searchByCity = $this->session->get('location')['city_url'];
            }
            $searchCity = $this->locationServices->getCityViaSearch($searchByCity);
 
            if($searchCity){
                $this->geocity = $searchCity;
            }
        }
 
        if(!$this->geocity){
            if (!empty($userLocation) && !empty($userLocation['country']) && strtoupper($userLocation['country']) == $country && !empty($userLocation['region']))
            {
                $this->geocity = GeodataGeocity::findFirst([
                    'conditions' => 'city = :loc_city: AND region=:loc_region: AND country = :loc_country:',
                    'bind'       => ['loc_city' => $userLocation['city'], 'loc_region'=>$userLocation['region'], 'loc_country' => $country]
                ]);
            }
        }
 
        if (!$this->geocity)
        {
            $this->geocity = GeodataGeocity::findFirst([
                'conditions' => 'city = :city: AND country = :country:',
                'bind'       => compact('city', 'country')
            ]);
        }
    }
 
 
    /**
     * Allow to globally initialize the controller in the request
     *
     * @Triggered on Controllers
     */
    public function initialize()
    {
        $this->assets->collection('header');
        $this->assets->collection('js-header');
        $this->assets->collection('footer');
 
        Tag::setTitle($this->config->get('site-name'));
        Tag::setTitleSeparator(", ");
 
        $this->view->setLayout('profile-layout');
 
        $this->view->setVars([
                'geocity' => $this->geocity,
                'user'    => $this->user,
                'user_id' => $this->user_id
            ]
        );
    }
 
    /**
     * Triggered after executing the controller/action method. As operation cannot be stopped, only use this event
     * to make clean up after execute the action
     *
     * @param $dispatcher
     *
     * @Triggered on Listeners/Controllers
     */
    public function afterExecuteRoute($dispatcher)
    {
        $this->view->setVars([
                'local_header_name' => $this->local_header_name,
            ]
        );
    }
 
    protected function _curl_fetch($url)
    {
        $crl = curl_init();
 
        curl_setopt($crl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
        curl_setopt($crl, CURLOPT_URL, $url);
        curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, 3);
 
        $ret = curl_exec($crl);
        curl_close($crl);
 
        return $ret;
    }
 
}
#15Apps\Frontend\Controllers\BaseController->beforeExecuteRoute(Object(Phalcon\Mvc\Dispatcher))
/home/finduslocal/public_html/apps/frontend/controllers/IndexController.php (31)
<?php
 
namespace  Apps\Frontend\Controllers;
 
 
use Apps\Commons\Models\Categories;
use Apps\Commons\Models\CategoriesToplevel;
use Apps\Commons\Models\CategoryKeyword;
use Apps\Commons\Models\Content;
use Apps\Commons\Models\FranchiseBystate;
use Apps\Commons\Models\GeodataGeocity;
use Apps\Commons\Models\GeodataUsstates;
use Phalcon\Dispatcher;
use Phalcon\Paginator\Adapter\Model;
 
class IndexController extends BaseController
{
    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
        $this->view->setLayout('profile-layout');
 
        if (!in_array($dispatcher->getActionName(), ['summary', 'job_opportunities', 'people'])):
            $this->assets->collection('header')
                ->addCss('/css/profile-ful.css', false);
            $this->assets->collection('header')
                ->addJs('/javascript/alljs.js', false)
                ->addJs('/tooltipjs/jquery.betterTooltip.js', false);
 
        endif;
 
        return parent::beforeExecuteRoute($dispatcher);
 
    }
 
    public function initialize()
    {
        $this->view->setLayout('profile-layout');
        $this->view->robots = 'true';
        return parent::initialize(); // TODO: Change the autogenerated stub
 
    }
 
    /**
     * Redirect depending on the city
     */
    public function indexAction()
    {
 
        return $this->response->redirect([
            'for'      => "frontent.region.city",
            'region'   => strtolower($this->geocity->region),
            'city_url' => $this->geocity->url_id
        ]);
 
    }
 
    /**
     * @param string $alphabet
     */
    public function franchisesAction($alphabet)
    {
        $states = GeodataUsstates::find([
            'order' => 'statetitle'
        ]);
 
        $this->assets->collection('header')
            ->addCss('/css/slide.css', false);
 
        $categories = Categories::find([
            'conditions' => 'parent_id = "0" AND status = "1"',
            'group'      => 'url_id',
            'order'      => 'name, sort_order'
        ]);
 
        /*$companies = Content::find([
            'columns'    => 'company, URLid',
            'conditions' => 'state = :state: AND city = :city: AND company LIKE :company: AND active = "1"',
            'bind'       => [
                'state'   => $this->geocity->region,
                'city'    => $this->geocity->city,
                'company' => $alphabet . '%'
            ],
            'order'      => 'company'
        ]);*/
 
        $franchise_bystate = FranchiseBystate::find([
            'conditions' => 'state = :state: AND company LIKE :company:',
            'bind'       => ['state' => $this->geocity->region, 'company' => $alphabet . '%'],
            'orderBy'    => 'company,'
        ]);
 
        $this->assets->collection('header')
            ->addCss('/css/profile_business-ful.css', false);
 
        $this->view->setVars(compact('states', 'categories', 'franchise_bystate'));
    }
 
 
    public function _showShoppingCategory($page)
    {
 
        $_cat         = CategoriesToplevel::findFirstByUrlId('shopping');
        $category_ids = explode(',', $_cat->mapped_rootcats);
        $category_ids = array_merge($category_ids, explode(',', $_cat->mapped_subcats));
 
        $contents = Content::find([
            'conditions' => 'state = :state: AND category_id IN ({category_ids:array}) AND active = "1"',
            "bind"       => [
                'state'        => $this->geocity->region,
                'category_ids' => $category_ids
            ]
        ]);
 
        // Create a Model paginator, show config rows by page starting from $page
        $paginator = new Model(
            [
                "data"  => $contents,
                "limit" => $this->config->default->get('companies_per_page'),
                "page"  => $page,
            ]
        );
 
        // Get the paginated results
        $pages = $paginator->getPaginate();
 
        $local_header_name =
            sprintf('Local %s in %s (%s)', 'shopping', $this->geocity->HasGeodataUsstates->statetitle,
                $this->geocity->region);
 
        $this->tag->appendTitle($local_header_name);
        $_pager_url   = [];
        $_pager_url[] = 'shopping';
 
        $pager_url                     = implode('/', $_pager_url);
        $this->view->pages             = $pages;
        $this->view->city              = null;
        $this->view->region            = null;
        $this->view->pager_url         = $pager_url;
        $this->view->local_header_name = $local_header_name;
 
        $this->helpers::addMetaTag('description',
            "Shopping In Your Local Area Or State will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
 
        $this->helpers::addMetaTag('keywords', "Shopping,company,reviews,directions,local,business hours");
        $this->helpers::addMetaTag('revisit-after', '1 days');
        $this->helpers::addMetaTag('rating', 'general');
        $this->helpers::addMetaTag('og:title', "Shopping  In Your Local Area Or State");
        $this->helpers::addMetaTag('og:type', 'website');
        $this->helpers::addMetaTag('og:url', $this->router->getRewriteUri());
        $this->helpers::addMetaTag('og:site_name', 'Find Us Local');
        $this->helpers::addMetaTag('og:description',
            "Shopping In Your Local Area Or State will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
        $this->helpers::addMetaTag('og:image', '//res.finduslocal.com/v3images/finduslocal-logo.png');
        $this->helpers::addMetaTag('robots', 'noindex,noarchive,nosnippet,follow');
 
        return $this->view->pick("index/shopping_listing");
    }
 
    /**
     * Output category page
     *
     * @param string $category
     */
    public function categoryAction($category, $page = null)
    {
        $category = $this->filter->sanitize($category, 'string');
 
        // Remove duplicate pages
        if ($page == 1 OR $page == "0")
        {
            return $this->response->redirect([
                'for'      => "frontent.index.category",
                'category' => $category
            ]);
        }
 
        if (is_null($page))
        {
            $page = 1;
        }
 
        if ($category == 'shopping')
        {
            return $this->_showShoppingCategory($page);
        }
 
        // Get Category
        $categoryObject   = Categories::findFirstByUrl_id($category);
        $category_ids     = [];
        $categoriesObject = null;
        $show_categories  = true;
 
        $radius = $this->request->get('radius', 'int', 50); //mill
 
        if ($categoryObject)
        {
            $category_ids = [$categoryObject->id];
 
            if ($categoryObject->parent_id == 0)
            {
                $categoriesObject = Categories::findByParent_id($categoryObject->id);
 
                foreach ($categoriesObject as $co):
                    array_push($category_ids, $co->id);
                endforeach;
            }
 
            $lat = $this->geocity->latitude;
            $lon = $this->geocity->longitude;
 
            $angle_radius = $radius / 111; // Every lat|lon degree° is ~ 69.40Mill
 
            //Fetch the list of companies
            $contents = Content::find([
                'conditions' => 'state = :state: AND category_id IN ({category_ids:array}) AND active = "1" AND lat BETWEEN :min_lat: AND :max_lat: AND lng BETWEEN :min_lon: AND :max_lon:',
                "bind"       => [
                    'state' => $this->geocity->region,
                    'category_ids' => $category_ids,
                    'min_lat'      => $lat - $angle_radius,
                    'max_lat'      => $lat + $angle_radius,
                    'min_lon'      => $lon - $angle_radius,
                    'max_lon'      => $lon + $angle_radius
                ]
            ]);
 
        } else
        {
 
            $categoryObject  = new Categories();
            $show_categories = false;
 
            $lat = $this->geocity->latitude;
            $lon = $this->geocity->longitude;
 
            $angle_radius = $radius / 111; // Every lat|lon degree° is ~ 69Mill
 
            //Fetch the list of companies
            $contents = Content::find([
                'conditions' => 'state = :state: AND URLid = :category: AND active = "1" AND lat BETWEEN :min_lat: AND :max_lat: AND lng BETWEEN :min_lon: AND :max_lon:',
                "bind"       => [
                    'state' => $this->geocity->region,
                    'category' => $category,
                    'min_lat'      => $lat - $angle_radius,
                    'max_lat'      => $lat + $angle_radius,
                    'min_lon'      => $lon - $angle_radius,
                    'max_lon'      => $lon + $angle_radius
                ]
            ]);
 
            if (!empty($contents))
            {
                $first_elm              = $contents->getFirst();
                $categoryObject->name   = !empty($first_elm) ? $first_elm->company : null;
                $categoryObject->url_id = $category;
            }
 
            $category_ids_array = [];
            foreach ($contents as $content)
            {
                $category_ids_array[$content->category_id] = $content->category_id;
            }
 
            if (!empty($category_ids_array))
            {
                $categoryObject->Keywords = CategoryKeyword::find([
                    'conditions' => 'category_id IN ({categoryids:array})',
                    'bind'       => ['categoryids' => array_keys($category_ids_array)],
                    'limit'      => 70,
                    'order'      => 'RAND()'
                ]);
            }
        }
 
 
        if ($contents->count() > 0)
        {
            // Get states
            $states = GeodataUsstates::find([
                'group' => 'statecode',
                'order' => 'statetitle'
            ]);
            /*$state_code_array = [];
            foreach ($contents as $content)
            {
                $state_code_array[$content->state] = $content->state;
            }
 
            if (!empty($state_code_array))
            {
                $states = GeodataUsstates::find([
                    'conditions' => 'statecode = ({statecode:array})',
                    "bind"       => ['statecode' => array_keys($state_code_array)],
                    'group'      => 'statecode',
                    'order'      => 'statetitle'
                ]);
            }*/
 
 
            // Create a Model paginator, show config rows by page starting from $page
            $paginator = new Model(
                [
                    "data"  => $contents,
                    "limit" => $this->config->default->get('companies_per_page'),
                    "page"  => $page,
                ]
            );
 
            // Get the paginated results
            $pages = $paginator->getPaginate();
 
            $this->local_header_name =
                sprintf('Local %s in %s (%s)', $categoryObject->name, $this->geocity->HasGeodataUsstates->statetitle,
                    $this->geocity->region);
 
            $this->tag->appendTitle("$categoryObject->name  In Your Local Area Or State");
 
            //Return variables to model
            $this->view->setVars(compact('pages', 'categoryObject', 'categoriesObject'));
 
            $this->view->navURL          = trim($this->router->getRewriteUri(), '/');
            $this->view->stateSet        = null;
            $this->view->radius          = $radius;
            $this->view->categorySet     = $categoryObject;
            $this->view->citySet         = null;
            $this->view->states          = $states;
            $this->view->show_categories = $show_categories;
            $this->helpers::addMetaTag('description',
                "$categoryObject->name In Your Local Area Or State will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
 
            $this->helpers::addMetaTag('keywords',
                "$categoryObject->name,company,reviews,directions,local,business hours");
            $this->helpers::addMetaTag('revisit-after', '1 days');
            $this->helpers::addMetaTag('rating', 'general');
            $this->helpers::addMetaTag('og:title', "$categoryObject->name  In Your Local Area Or State");
            $this->helpers::addMetaTag('og:type', 'website');
            $this->helpers::addMetaTag('og:url', $this->router->getRewriteUri());
            $this->helpers::addMetaTag('og:site_name', 'Find Us Local');
            $this->helpers::addMetaTag('og:description',
                "$categoryObject->name In Your Local Area Or State will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
            $this->helpers::addMetaTag('og:image', '//res.finduslocal.com/v3images/finduslocal-logo.png');
            $this->helpers::addMetaTag('robots', 'noindex,noarchive,nosnippet,follow');
 
            return $this->view->pick("index/categories_listing");
        }
        /*
                //$content_searchfields = ContentSearchfields::find()
 
                // Check is content url
                $is_content = false;
 
                $contents = Content::find([
                    'conditions' => 'state = :state: AND URLid = :category: AND active = "1"',
                    "bind"       => ['state' => $this->geocity->region, 'category' => $category]
                ]);
 
                if ($contents->count() > 0)
                {
                    // Get first record of $contents
                    $first_company = $contents->getFirst();
 
                    // Get company of another state
                    $states = Content::find([
                        'conditions' => 'URLid = :category:',
                        "bind"       => ['category' => $category],
                        'group'      => 'state',
                        'order'      => 'state'
                    ]);
 
                    $states_array = [];
                    foreach ($states as $state)
                    {
                        $url_id = $state->HasState->url_id;
 
                        $count = Content::count([
                            'conditions' => 'URLid = :category: AND state = :state:',
                            "bind"       => ['category' => $category, 'state' => $state->state],
                        ]);
 
                        $states_array[$url_id] = [
                            'count' => $count,
                            'name'  => sprintf('%s (%s)', $state->HasState->statetitle, $state->state),
                            'url'   => $this->url->get([
                                'for'      => 'frontent.index.two_url',
                                'category' => $first_company->URLid,
                                'url'      => $url_id
                            ])
                        ];
                    }
 
                    $show_bottom_header = true;
 
                    // Create a Model paginator, show config rows by page starting from $page
                    $paginator = new Model(
                        [
                            "data"  => $contents,
                            "limit" => $this->config->default->get('companies_per_page'),
                            "page"  => $page,
                        ]
                    );
 
                    // Get the paginated results
                    $pages = $paginator->getPaginate();
 
                    $this->local_header_name = sprintf('Local %s in Your Local Area Or State', $first_company->company);
 
                    $this->tag->appendTitle($this->local_header_name);
 
                    //Return variables to model
                    $this->view->setVars(compact('first_company', 'pages', 'show_bottom_header', 'states_array'));
 
                    $this->helpers::addMetaTag('description',
                        "$categoryObject In Your Local Area Or State will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
 
                    $this->helpers::addMetaTag('keywords', "$categoryObject,company,reviews,directions,local,business hours");
                    $this->helpers::addMetaTag('revisit-after', '1 days');
                    $this->helpers::addMetaTag('rating', 'general');
                    $this->helpers::addMetaTag('og:title', "$categoryObject  In Your Local Area Or State");
                    $this->helpers::addMetaTag('og:type', 'website');
                    $this->helpers::addMetaTag('og:url', $this->router->getRewriteUri());
                    $this->helpers::addMetaTag('og:site_name', 'Find Us Local');
                    $this->helpers::addMetaTag('og:description', "$categoryObject->name In Your Local Area Or State will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
                    $this->helpers::addMetaTag('og:image', '//res.finduslocal.com/v3images/finduslocal-logo.png');
                    $this->helpers::addMetaTag('robots', 'noindex,noarchive,nosnippet,follow');
 
                    return $this->view->pick("index/company_listing");
 
                }
 
 
                return $this->response->redirect(['for' => 'home'], false, 404);
        */
    }
 
    /**
     * @param string $category
     * @param string $url
     * @param null   $page
     *
     * @return \Phalcon\Mvc\View
     */
    public function _showShoppingCategoryWithRegion($region, $page)
    {
        if ($geodata_us_state = GeodataUsstates::findFirstByUrl_id($region))
        {
 
        } else
        {
            return $this->dispatcher->forward(array(
                "controller" => "index",
                "action" => "page404"
            ));
        }
 
        $_cat         = CategoriesToplevel::findFirstByUrlId('shopping');
        $category_ids = explode(',', $_cat->mapped_rootcats);
        $category_ids = array_merge($category_ids, explode(',', $_cat->mapped_subcats));
 
        $contents = Content::find([
            'conditions' => 'state = :state: AND category_id IN ({category_ids:array}) AND active = "1"',
            "bind"       => [
                'state'        => $geodata_us_state->statecode,
                'category_ids' => $category_ids
            ]
        ]);
 
        // Create a Model paginator, show config rows by page starting from $page
        $paginator = new Model(
            [
                "data"  => $contents,
                "limit" => $this->config->default->get('companies_per_page'),
                "page"  => $page,
            ]
        );
 
        // Get the paginated results
        $pages = $paginator->getPaginate();
 
//        $local_header_name = sprintf('Local %s in %s (%s)', 'shopping', $geodata_geocity->HasGeodataUsstates->statetitle, $geodata_geocity->region);
        $local_header_name = sprintf('Local %s in %s (%s)', 'shopping',"", "");
 
        $this->tag->appendTitle($local_header_name);
        $_pager_url   = [];
        $_pager_url[] = 'shopping';
        if ($geodata_us_state)
        {
            $_pager_url[] = $geodata_us_state->url_id;
        }
 
        $pager_url                     = implode('/', $_pager_url);
        $this->view->pages             = $pages;
        $this->view->city              = null;
        $this->view->region            = $geodata_us_state;
        $this->view->pager_url         = $pager_url;
        $this->view->local_header_name = $local_header_name;
 
        $this->helpers::addMetaTag('description',
            "Shopping In  $geodata_us_state->statetitle ($geodata_us_state->statecode) will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
 
        $this->helpers::addMetaTag('keywords',
            "Shopping,company,reviews,directions,$geodata_us_state->statetitle,$geodata_us_state->statecode,local,business hours");
        $this->helpers::addMetaTag('revisit-after', '1 days');
        $this->helpers::addMetaTag('rating', 'general');
        $this->helpers::addMetaTag('og:title',
            "Shopping In  $geodata_us_state->statetitle ($geodata_us_state->statecode)");
        $this->helpers::addMetaTag('og:type', 'website');
        $this->helpers::addMetaTag('og:url', $this->router->getRewriteUri());
        $this->helpers::addMetaTag('og:site_name', 'Find Us Local');
        $this->helpers::addMetaTag('og:description',
            "Shopping In  $geodata_us_state->statetitle ($geodata_us_state->statecode) will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
        $this->helpers::addMetaTag('og:image', '//res.finduslocal.com/v3images/finduslocal-logo.png');
        $this->helpers::addMetaTag('robots', 'noindex,noarchive,nosnippet,follow');
 
        return $this->view->pick("index/shopping_listing");
    }
 
    /**
     * @param string $category
     * @param string $url
     * @param null   $page
     *
     * @return \Phalcon\Mvc\View
     */
    public function two_urlAction($category, $url, $page = null)
    {
        $caregory_url = $this->filter->sanitize($category, 'string');
        $url          = $this->filter->sanitize($url, 'string');
        // Remove duplicate pages
        if ($page == 1 OR $page == "0")
        {
            return $this->response->redirect([
                'for'      => "frontent.index.two_url",
                'category' => $caregory_url,
                'url'      => $url
            ]);
        }
 
        if (is_null($page))
        {
            $page = 1;
        }
 
        if ($caregory_url == 'shopping')
        {
            return $this->_showShoppingCategoryWithRegion($url, $page);
        }
// else
//        {
//            return $this->_showCategoryWithRegion($category, $url, $page);
//        }
 
 
        $category       = Categories::findFirstByUrl_id($caregory_url);
        $name_company   = false;
        $categoryObject = null;
 
        $geodata_us_state = GeodataUsstates::findFirstByUrl_id($url);
        $category_ids     = [];
 
        if (!$category)
        {
            $category        = new Categories();
            $show_categories = false;
 
            //Fetch the list of companies
            $contents = Content::find([
                'conditions' => 'state = :state: AND URLid = :category: AND active = "1"',
                "bind"       => ['state' => $geodata_us_state->statecode, 'category' => $caregory_url]
            ]);
 
            if (!empty($contents))
            {
                $name_company = true;
 
                $first_elm = $contents->getFirst();
                $category->name = $first_elm->company;
                $category->url_id = $caregory_url;
 
                $category_ids_array = [];
                foreach ($contents as $content)
                {
                    $category_ids_array[$content->category_id] = $content->category_id;
                }
 
                if (!empty($category_ids_array))
                {
                    $category_ids = array_keys($category_ids_array);
                    $category->Keywords = CategoryKeyword::find([
                        'conditions' => 'category_id IN ({categoryids:array})',
                        'bind' => ['categoryids' => array_keys($category_ids_array)],
                        'limit' => 70,
                        'order' => 'RAND()'
                    ]);
                }
            }
        }
        else {
            $category_ids = [$category->id];
            if ($category->parent_id == 0)
            {
                $parent_categories = Categories::findByParent_id($category->id);
 
                foreach ($parent_categories as $item)
                {
                    array_push($category_ids, $item->id);
                }
            }
 
            if (!empty($geodata_us_state))
            {
                $contents = Content::find([
                    'conditions' => 'state = :state:  AND category_id IN ({category_ids:array}) AND active = "1"',
                    "bind"       => [
                        'state'        => $geodata_us_state->statecode,
                        'category_ids' => $category_ids
                    ]
                ]);
            }
        }
 
        if (!empty($contents))
        {
            // Get first record of $contents
            $first_company = $contents->getFirst();
 
            // Get company of another cites
            $cites = Content::find([
                'conditions' => 'state = :state:  AND category_id IN ({category_ids:array}) AND active = "1"',
                "bind"       => ['category_ids' => $category_ids, 'state' => $geodata_us_state->statecode],
                'group'      => 'city',
                'order'      => 'city'
            ]);
 
            $cites_array = [];
            foreach ($cites as $city)
            {
                $first_letter = $city->city{0};
                $url_id       = $city->HasCity->url_id;
 
                if (empty($cites_array[$first_letter]))
                {
                    $cites_array[$first_letter] = [];
                }
 
                $count = Content::count([
                    'conditions' => 'category_id IN ({category_ids:array}) AND active = "1" AND state = :state: AND city = :city:',
                    "bind"       => [
                        'category_ids' => $category_ids,
                        'state'        => $geodata_us_state->statecode,
                        'city'         => $city->city
                    ]
                ]);
 
                $cites_array[$first_letter][$url_id] = [
                    'count' => $count,
                    'name'  => $city->city,
                    'url'   => $this->url->get([
                        'for'   => 'frontent.index.three_url',
                        'url_1' => $category->url_id,
                        'url_2' => $geodata_us_state->url_id,
                        'url_3' => $url_id
                    ])
                ];
            }
 
            // Create a Model paginator, show config rows by page starting from $page
            $paginator = new Model(
                [
                    "data"  => $contents,
                    "limit" => $this->config->default->get('companies_per_page'),
                    "page"  => $page,
                ]
            );
 
            // Get the paginated results
            $pages = $paginator->getPaginate();
 
            if (!empty($first_company))
            {
                $show_bottom_header = true;
 
                $this->local_header_name =
                    "Local $category->name In  $geodata_us_state->statetitle ($geodata_us_state->statecode)";
            }
 
            $this->tag->appendTitle("$category->name In  $geodata_us_state->statetitle ($geodata_us_state->statecode)");
 
            //Return variables to model
            $this->view->setVars(compact('first_company', 'pages', 'show_bottom_header', 'cites_array',
                'geodata_us_state', 'url'));
            $this->view->navURL      = ltrim($this->router->getRewriteUri(), '/');
            $this->view->stateSet    = $geodata_us_state;
            $this->view->categorySet = $category;
            $this->view->citySet     = null;
 
            $this->helpers::addMetaTag('description',
                "$category->name In  $geodata_us_state->statetitle ($geodata_us_state->statecode) will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
 
            $this->helpers::addMetaTag('keywords',
                "$category->name,company,reviews,directions,$geodata_us_state->statetitle,$geodata_us_state->statecode,local,business hours");
            $this->helpers::addMetaTag('revisit-after', '1 days');
            $this->helpers::addMetaTag('rating', 'general');
            $this->helpers::addMetaTag('og:title',
                "$category->name In  $geodata_us_state->statetitle ($geodata_us_state->statecode)");
            $this->helpers::addMetaTag('og:type', 'website');
            $this->helpers::addMetaTag('og:url', $this->router->getRewriteUri());
            $this->helpers::addMetaTag('og:site_name', 'Find Us Local');
            $this->helpers::addMetaTag('og:description',
                "$category->name In  $geodata_us_state->statetitle ($geodata_us_state->statecode) will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
            $this->helpers::addMetaTag('og:image', '//res.finduslocal.com/v3images/finduslocal-logo.png');
            $this->helpers::addMetaTag('robots', 'noindex,noarchive,nosnippet,follow');
 
            return $this->view->pick("index/cites_listing");
        }
 
        return $this->dispatcher->forward(array(
            "controller" => "index",
            "action" => "page404"
        ));
    }
 
 
    /**
     * @param string $region
     * @param string $city
     * @param null   $page
     *
     * @return \Phalcon\Mvc\View
     */
    protected function _showShoppingCategoryWithRegionAndCity($region, $city, $page)
    {
 
        if ($geodata_us_state = GeodataUsstates::findFirstByUrl_id($region))
        {
            $geodata_geocity = GeodataGeocity::findFirst([
                'conditions' => 'region = :region: AND url_id = :url:',
                "bind"       => ['region' => $geodata_us_state->statecode, 'url' => $city]
            ]);
 
            if (!$geodata_geocity)
            {
                return $this->dispatcher->forward(array(
                    "controller" => "index",
                    "action" => "page404"
                ));
            }
        } else
        {
            return $this->dispatcher->forward(array(
                "controller" => "index",
                "action" => "page404"
            ));
        }
 
        $_cat         = CategoriesToplevel::findFirstByUrlId('shopping');
        $category_ids = explode(',', $_cat->mapped_rootcats);
        $category_ids = array_merge($category_ids, explode(',', $_cat->mapped_subcats));
 
        $contents = Content::find([
            'conditions' => 'state = :state: AND city=:city: AND category_id IN ({category_ids:array}) AND active = "1"',
            "bind"       => [
                'state'        => $geodata_geocity->region,
                'city'         => $geodata_geocity->city,
                'category_ids' => $category_ids
            ]
        ]);
 
        // Create a Model paginator, show config rows by page starting from $page
        $paginator = new Model(
            [
                "data"  => $contents,
                "limit" => $this->config->default->get('companies_per_page'),
                "page"  => $page,
            ]
        );
 
        // Get the paginated results
        $pages = $paginator->getPaginate();
 
        $local_header_name =
            sprintf('Local %s in %s (%s)', 'shopping', $geodata_geocity->HasGeodataUsstates->statetitle,
                $geodata_geocity->region);
 
        $this->tag->appendTitle($local_header_name);
 
        $_pager_url   = [];
        $_pager_url[] = 'shopping';
        $_pager_url[] = $geodata_us_state->url_id;
        $_pager_url[] = $geodata_geocity->url_id;
 
        $pager_url                     = implode('/', $_pager_url);
        $this->view->pages             = $pages;
        $this->view->city              = $geodata_geocity;
        $this->view->region            = $geodata_us_state;
        $this->view->pager_url         = $pager_url;
        $this->view->local_header_name = $local_header_name;
 
        $this->helpers::addMetaTag('description',
            "Shopping In $geodata_geocity->city, $geodata_us_state->statetitle ($geodata_geocity->region) will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
 
        $this->helpers::addMetaTag('keywords',
            "Shopping,company,reviews,directions,$geodata_us_state->statetitle,$geodata_geocity->region,$geodata_geocity->city,local,business hours");
        $this->helpers::addMetaTag('revisit-after', '1 days');
        $this->helpers::addMetaTag('rating', 'general');
        $this->helpers::addMetaTag('og:title',
            "Shopping In $geodata_geocity->city, $geodata_us_state->statetitle ($geodata_geocity->region)");
        $this->helpers::addMetaTag('og:type', 'website');
        $this->helpers::addMetaTag('og:url', $this->router->getRewriteUri());
        $this->helpers::addMetaTag('og:site_name', 'Find Us Local');
        $this->helpers::addMetaTag('og:description',
            "Shopping In $geodata_geocity->city, $geodata_us_state->statetitle ($geodata_geocity->region) will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
        $this->helpers::addMetaTag('og:image', '//res.finduslocal.com/v3images/finduslocal-logo.png');
        $this->helpers::addMetaTag('robots', 'noindex,noarchive,nosnippet,follow');
 
        return $this->view->pick("index/shopping_listing");
 
    }
 
    /**
     * @param string $category
     * @param string $region
     * @param string $city
     * @param null   $page
     *
     * @return \Phalcon\Mvc\View
     */
    protected function _showCategoryWithRegionAndCity($category, $region, $city, $page)
    {
 
        if ($geodata_us_state = GeodataUsstates::findFirstByUrl_id($region))
        {
            $geodata_geocity = GeodataGeocity::findFirst([
                'conditions' => 'region = :region: AND url_id = :url:',
                "bind"       => ['region' => $geodata_us_state->statecode, 'url' => $city]
            ]);
 
            if (!$geodata_geocity)
            {
                return $this->dispatcher->forward(array(
                    "controller" => "index",
                    "action" => "page404"
                ));
            }
        } else
        {
            return $this->dispatcher->forward(array(
                "controller" => "index",
                "action" => "page404"
            ));
        }
 
 
        $category_ids = [$category->id];
 
        $parent_categories = null;
 
        if ($category->parent_id == 0)
        {
            $parent_categories = Categories::findByParent_id($category->id);
 
            foreach ($parent_categories as $item)
            {
                array_push($category_ids, $item->id);
            }
        }
 
        $lat = $geodata_geocity->latitude;
        $lon = $geodata_geocity->longitude;
        $radius = $this->request->get('radius', 'int', 50); //mill
 
        $angle_radius = $radius / 111; // Every lat|lon degree° is ~ 69Mill
 
        //Fetch the list of companies by state, city and categories
        $contents = Content::find([
            'conditions' => 'state = :state: AND city=:city: AND category_id IN ({category_ids:array}) AND active = "1" AND lat BETWEEN :min_lat: AND :max_lat: AND lng BETWEEN :min_lon: AND :max_lon:',
            "bind"       => [
                'state'        => $geodata_geocity->region,
                'city'         => $geodata_geocity->city,
                'category_ids' => $category_ids,
                'min_lat'      => $lat - $angle_radius,
                'max_lat'      => $lat + $angle_radius,
                'min_lon'      => $lon - $angle_radius,
                'max_lon'      => $lon + $angle_radius
            ]
        ]);
 
        // Create a Model paginator, show config rows by page starting from $page
        $paginator = new Model(
            [
                "data"  => $contents,
                "limit" => $this->config->default->get('companies_per_page'),
                "page"  => $page,
            ]
        );
 
        // Get the paginated results
        $pages = $paginator->getPaginate();
 
        $local_header_name =
            "$category->name In $geodata_geocity->city, $geodata_us_state->statetitle ($geodata_geocity->region)";
 
        $this->tag->appendTitle($local_header_name);
 
        $this->view->navURL           = ltrim($this->router->getRewriteUri(), '/');
        $this->view->radius           = $radius;
        $this->view->stateSet         = $geodata_us_state;
        $this->view->categorySet      = $category;
        $this->view->citySet          = $geodata_geocity;
        $this->view->pages            = $pages;
        $this->view->categoryObject   = $category;
        $this->view->categoriesObject = $parent_categories;
 
        $this->helpers::addMetaTag('description',
            "$category->name In $geodata_geocity->city, $geodata_us_state->statetitle ($geodata_geocity->region) will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
 
        $this->helpers::addMetaTag('keywords',
            "$category->name,company,reviews,directions,$geodata_us_state->statetitle,$geodata_geocity->region,$geodata_geocity->city,local,business hours");
        $this->helpers::addMetaTag('revisit-after', '1 days');
        $this->helpers::addMetaTag('rating', 'general');
        $this->helpers::addMetaTag('og:title',
            "$category->name In $geodata_geocity->city, $geodata_us_state->statetitle ($geodata_geocity->region)");
        $this->helpers::addMetaTag('og:type', 'website');
        $this->helpers::addMetaTag('og:url', $this->router->getRewriteUri());
        $this->helpers::addMetaTag('og:site_name', 'Find Us Local');
        $this->helpers::addMetaTag('og:description',
            "$category->name In $geodata_geocity->city, $geodata_us_state->statetitle ($geodata_geocity->region) will keep their profiles up to date so you can easily get their Phone Numbers, Address, Reviews, or Business Hours");
        $this->helpers::addMetaTag('og:image', '//res.finduslocal.com/v3images/finduslocal-logo.png');
        $this->helpers::addMetaTag('robots', 'noindex,noarchive,nosnippet,follow');
 
        return $this->view->pick("index/categories_listing");
    }
 
    /**
     * @param string $category
     * @param string $region
     * @param string $city
     * @param null   $page
     *
     * @return \Phalcon\Mvc\View
     */
    protected function _showCategoryWithRegion($category, $region, $page)
    {
 
        if ($geodata_us_state = GeodataUsstates::findFirstByUrl_id($region))
        {
        } else
        {
            return $this->dispatcher->forward(array(
                "controller" => "index",
                "action" => "page404"
            ));
        }
 
        $category_ids = [$category->id];
 
        $parent_categories = null;
 
        if ($category->parent_id == 0)
        {
            $parent_categories = Categories::findByParent_id($category->id);
 
            foreach ($parent_categories as $item)
            {
                array_push($category_ids, $item->id);
            }
        }
 
 
        //Fetch the list of companies by state, city and categories
        $contents = Content::find([
            'conditions' => 'state = :state: AND category_id IN ({category_ids:array}) AND active = "1"',
            "bind"       => [
                'state'        => $geodata_us_state->statecode,
                'category_ids' => $category_ids
            ]
        ]);
 
        // Create a Model paginator, show config rows by page starting from $page
        $paginator = new Model(
            [
                "data"  => $contents,
                "limit" => $this->config->default->get('companies_per_page'),
                "page"  => $page,
            ]
        );
 
        // Get the paginated results
        $pages = $paginator->getPaginate();
 
        if ($category == 'shopping')
        {
            $local_header_name =
                sprintf('Local %s in %s', 'shopping', $geodata_us_state->statetitle);
        } else
        {
            $local_header_name =
                sprintf('Local %s in %s', $category->name, $geodata_us_state->statetitle);
        }
        $this->tag->appendTitle($local_header_name);
 
 
        $this->view->navURL           = ltrim($this->router->getRewriteUri(), '/');
        $this->view->stateSet         = $geodata_us_state;
        $this->view->categorySet      = $category;
        $this->view->pages            = $pages;
        $this->view->categoryObject   = $category;
        $this->view->categoriesObject = $parent_categories;
 
        return $this->view->pick("index/categories_listing");
    }
 
    /**
     * @param string $url_1
     * @param string $url_2
     * @param string $url_3
     * @param null   $page
     *
     * @return \Phalcon\Mvc\View
     */
    public function three_urlAction($url_1, $url_2, $url_3, $page = null)
    {
        // Remove duplicate pages
        if ($page == 1 OR $page == "0")
        {
            return $this->response->redirect([
                'for'   => "rontent.index.three_url",
                'url_1' => $url_1,
                'url_2' => $url_2,
                'url_3' => $url_3
            ]);
        }
 
        if (is_null($page))
        {
            $page = 1;
        }
 
        if ($url_1 == 'shopping')
        {
            return $this->_showShoppingCategoryWithRegionAndCity($url_2, $url_3, $page);
        }
 
        $categories = Categories::findFirstByUrl_id($url_1);
        if ($categories)
        {
            return $this->_showCategoryWithRegionAndCity($categories, $url_2, $url_3, $page);
        }
 
 
        // If $category is state
        if ($geodata_us_state = GeodataUsstates::findFirstByUrl_id($url_2))
        {
            $geodata_geocity = GeodataGeocity::findFirst([
                'conditions' => 'region = :region: AND url_id = :url:',
                "bind"       => ['region' => $geodata_us_state->statecode, 'url' => $url_3]
            ]);
 
            if ($geodata_geocity)
            {
                $lat = $geodata_geocity->latitude;
                $lon = $geodata_geocity->longitude;
                $radius = $this->request->get('radius', 'int', 5); //mill
 
                /*$angle_radius = $radius / 111; // Every lat|lon degree° is ~ 111Km
                $min_lat = $lat - $angle_radius;
                $max_lat = $lat + $angle_radius;
                $min_lon = $lon - $angle_radius;
                $max_lon = $lon + $angle_radius;*/
 
                $contents = Content::find([
                    'conditions' => 'state = :state: AND city = :city: AND URLid = :url:',
                    "bind"       => [
                        'state' => $geodata_us_state->statecode,
                        'city'  => $geodata_geocity->city,
                        'url'   => $url_1,
 
                    ]
                ]);
 
 
                // Get first record of $contents
                $first_company = $contents->getFirst();
 
                // Create a Model paginator, show config rows by page starting from $page
                $paginator = new Model(
                    [
                        "data"  => $contents,
                        "limit" => $this->config->default->get('companies_per_page'),
                        "page"  => $page,
                    ]
                );
 
                // Get the paginated results
                $pages = $paginator->getPaginate();
 
                if (!empty($first_company))
                {
                    $show_bottom_header = true;
 
                    $this->local_header_name =
                        sprintf('Local %s in %s of state %s (%s)', $first_company->company, $geodata_geocity->city,
                            $geodata_us_state->statetitle, $geodata_us_state->statecode);
                }
 
                $this->tag->appendTitle($this->local_header_name);
 
                //Return variables to model
                $this->view->setVars(compact('first_company', 'pages', 'show_bottom_header', 'geodata_us_state',
                    'geodata_geocity', 'url_1', 'url_2', 'url_3'));
 
                return $this->view->pick("index/city_listing");
            }
        }
 
        return $this->dispatcher->forward(array(
            "controller" => "index",
            "action" => "page404"
        ));
 
    }
 
    /**
     * Show owner (people) page
     *
     * @param string $category
     * @param string $region
     * @param string $city
     * @param string $owner
     */
    public function peopleAction($category, $region, $city, $owner, $company)
    {
        $type             = 'people';
        $geodata_usstates = GeodataUsstates::findFirstByUrl_id($region);
        if (!empty($geodata_usstates))
        {
            $geodata_geocity = GeodataGeocity::findFirst([
                'conditions' => 'region = :region: AND url_id = :url:',
                "bind"       => ['region' => $geodata_usstates->statecode, 'url' => $city]
            ]);
 
            $categories = Categories::findFirstByUrl_id($category);
 
            if (!empty($geodata_geocity) && !empty($categories))
            {
                $content = Content::findFirst([
                    'conditions' => 'state = :state: AND URLid = :url: AND city = :city:',
                    'bind'       => [
                        'state' => $geodata_usstates->statecode,
                        'url'   => $company,
                        'city'  => $geodata_geocity->city
                    ]
                ]);
 
                if (!empty($content) AND $content->isOwner() AND $content->getOwnerNameUrl() == $owner)
                {
                    $this->assets->collection('header')
                        ->addCss('/css/profile_business-ful.css', false);
 
                    $this->tag->appendTitle(sprintf('%s %s in %s, %s %s',
                        $content->getOwnerName(), $categories->name, $content->city, $content->state, $content->zip));
 
                    $featured_businesses = Content::find([
                        'conditions' => 'state = :state: AND featured = "1" AND city = :city:',
                        'bind'       => ['state' => $geodata_usstates->statecode, 'city' => $geodata_geocity->city],
                        'order'      => 'RAND()',
                        'limit'      => 4
                    ]);
 
                    $this->assets->collection('header')
                        ->addJs('/review_systemajax/reviewsystem.js', false)
                        ->addJs('/javascript/alljs.js', false)
                        ->addJs('https://gdc.indeed.com/ads/apiresults.js', false, false)
                        ->addJs('/tooltipjs/jquery.betterTooltip.js', false);
 
                    $reviewcontainer = true;
 
                    $this->view->wallpaperbox =
                        $this->_getWallpaperBox($geodata_usstates->statecode, $geodata_geocity->city);
 
                    $this->view->setVars(compact('content', 'categories', 'geodata_geocity', 'geodata_usstates',
                        'this_url', 'featured_businesses', 'type', 'reviewcontainer'));
 
                    return $this->view->pick("index/profile/people");
                }
            }
        }
 
        return $this->dispatcher->forward(array(
            "controller" => "index",
            "action" => "page404"
        ));
 
    }
 
    /**
     * @param string      $category
     * @param string      $region
     * @param string      $city
     * @param string      $company
     * @param string      $street
     * @param string|null $type
     */
    public function summaryAction($category, $region, $city, $company, $street = null, $type = null, $phone = null)
    {
 
 
        if (!$type)
        {
            $type = $this->dispatcher->getParam('type', null, null);
        }
 
        if (!$street)
        {
            $street = $this->dispatcher->getParam('street', null, null);
        }
        $phone = $this->dispatcher->getParam('phone', null, null);
 
        $geodata_usstates = GeodataUsstates::findFirstByUrl_id($region);
 
        if ($geodata_usstates)
        {
            $geodata_geocity = GeodataGeocity::findFirst([
                'conditions' => 'region = :region: AND url_id = :url:',
                "bind"       => ['region' => $geodata_usstates->statecode, 'url' => $city]
            ]);
 
 
            $categories = Categories::findFirstByUrl_id($category);
 
            if ($geodata_geocity && $categories)
            {
 
                if ($street)
                {
                    $content = Content::findFirst([
                        'conditions' => 'state = :state: AND URLid = :url: AND address_URLid = :street: AND city = :city:',
//                        'columns' => 'id,content_id',
                        'bind'       => [
                            'state'  => $geodata_usstates->statecode,
                            'url'    => $company,
                            'street' => $street,
                            'city'   => $geodata_geocity->city
                        ]
                    ]);
                } else
                {
                    $content = Content::findFirst([
                        'conditions' => 'state = :state: AND URLid = :url: AND city = :city:',
//                        'columns' => 'id,content_id',
                        'bind'       => [
                            'state' => $geodata_usstates->statecode,
                            'url'   => $company,
                            'city'  => $geodata_geocity->city
                        ]
                    ]);
                }
 
                if ($content)
                {
                    $this->assets->collection('header')
                        ->addCss('/css/profile_business-ful.css', false);
 
                    $featured_businesses = Content::find([
                        'conditions' => 'category_id = :category_id: AND plan_id != 0 AND areacode = :areacode:',
                        'bind'       => ['category_id' => $categories->id, 'areacode' => $geodata_geocity->areaCode],
                        'order'      => 'RAND()',
                        'limit'      => 4
                    ]);
                    $this->assets->collection('header')
                        ->addJs('/review_systemajax/reviewsystem.js', false)
                        ->addJs('/javascript/alljs.js', false)
                        ->addJs('https://gdc.indeed.com/ads/apiresults.js', false, false)
                        ->addJs('/tooltipjs/jquery.betterTooltip.js', false);
 
                    $hasState = $content->HasState;
                    $hasCity = $content->HasCity;
                    $this->view->setVar('hasState',$hasState);
                    $this->view->setVar('hasCity',$hasCity);
 
                    if (empty($content->meta_keywords))
                    {
                        // Taqueria El Chino,New Rochelle,New York, NY, 10801,Restaurants and Cafes, hours, directions, phone number, reviews
                        $content->meta_keywords = sprintf('%s, %s, %s, %s, %s, %s, hours, directions, phone number, reviews', $content->company, $content->city, $hasState->statetitle, $content->state, $content->zip, $categories->name);
                        $content->meta_keywords = str_replace(',,', ',', $content->meta_keywords);
                        switch ($type)
                        {
                            case 'social':
                                // Taqueria El Chino facebook page, social,reputation,Taqueria El Chino,New Rochelle,New York, NY, 10801,
                                $content->meta_keywords = sprintf('%s facebook page, social,reputation,,%s,%s,%s,%s, %s,', $content->company, $content->company, $content->city, $hasState->statetitle, $content->state, $content->zip);
                                break;
                            case 'reports':
                                // traffic,social media, followers,Taqueria El Chino,New Rochelle,New York, NY, 10801,
                                $content->meta_keywords = sprintf('traffic,social media, followers,%s,%s,%s, %s, %s,', $content->company, $content->city, $hasState->statetitle, $content->state, $content->zip);
                                break;
                            case 'directions':
                                // directions,Taqueria El Chino,New Rochelle,New York, NY, 10801,
                                $content->meta_keywords = sprintf('directions,%s,%s,%s, %s, %s,', $content->company, $content->city, $hasState->statetitle, $content->state, $content->zip);
                                break;
                            case 'reviews':
                                // reviews,feedback,Taqueria El Chino,New Rochelle,New York, NY, 10801,,customer service
                                $content->meta_keywords = sprintf('reviews,feedback,%s,%s,%s, %s, %s,,customer service', $content->company, $content->city, $hasState->statetitle, $content->state, $content->zip);
                                break;
                            case 'job':
                                // jobs,job opportunities,Taqueria El Chino,jobs in New Rochelle,New York, NY, 10801,,New Rochelle jobs,
                                $content->meta_keywords = sprintf('jobs,job opportunities,%s,jobs in %s,%s, %s, %s,,%s jobs,', $content->company, $content->city, $hasState->statetitle, $content->state, $content->zip, $content->city);
                                break;
                            case 'phone':
                                // "phone,{$keywordAdd1} call, phone number, {$company},{$city},{$statetitle}, {$state}, {$zip},{$addmetaaddress}, dial{$keywordAdd2}")
                                $content->meta_keywords = sprintf('%s,phone, call, phone number, %s,%s,%s, %s, %s, dial', $phone, $content->company, $content->city, $hasState->statetitle, $content->state, $content->zip, $content->city);
                                break;
                        }
                    }
                    if (empty($content->meta_title))
                    {
                        $content->meta_title = sprintf('%s in %s, %s %s Directions and Hours and Reviews', $content->company, $content->city, $content->state, $content->zip);
 
                        switch ($type)
                        {
                            case 'social':
                                // Taqueria El Chino in New Rochelle, NY Facebook Google Plus Twitter Social Media
                                $content->meta_title = sprintf('%s in %s, %s Facebook Google Plus Twitter Social Media', $content->company, $content->city, $content->state);
                                break;
                            case 'reports':
                                // Social Media for Taqueria El Chino in New Rochelle, NY. Number of Facebook Fans, Twitter Followers For Taqueria El Chino
                                $content->meta_title = sprintf('Social Media for %s in %s, %s. Number of Facebook Fans, Twitter Followers For %s', $content->company, $content->city, $content->state, $content->company);
                                break;
                            case 'directions':
                                // Taqueria El Chino in New Rochelle, NY 10801 Directions
                                $content->meta_title = sprintf('%s in %s, %s %s Directions', $content->company, $content->city, $content->state, $content->zip);
                                break;
                            case 'reviews':
                                // Reviews for Taqueria El Chino in New Rochelle, NY. Reputation of Taqueria El Chino.
                                $content->meta_title = sprintf('Reviews for %s in %s, %s. Reputation of %s.', $content->company, $content->city, $content->state, $content->company);
                                break;
                            case 'job':
                                // Find Job Opportunities and Jobs in New Rochelle, NY - Taqueria El Chino
                                $content->meta_title = sprintf('Find Job Opportunities and Jobs in %s, %s - %s', $content->city, $content->state, $content->company);
                                break;
                            case 'phone':
                                // 914-636-2197 Phone Number For Taqueria El Chino in New Rochelle, NY 10801
                                $content->meta_title = sprintf('%s Phone Number For %s in %s, %s %s', $phone, $content->company, $content->city, $content->state, $content->zip);
                                break;
                        }
                    }
                    $this->tag->setTitle($content->meta_title);
 
                    if (empty($content->meta_description))
                    {
                        $content->meta_description = sprintf('Get %s phone number in %s, %s %s %s, %s Reviews', $content->company, $content->city, $content->state, $content->zip, $categories->name, $content->company);
 
                        switch ($type)
                        {
                            case 'social':
                                // Get Social Facebook, Twitter, Google Plus feeds for Taqueria El Chino in New Rochelle, NY. View the social reputation of Taqueria El Chino.
                                $content->meta_description = sprintf('Get Social Facebook, Twitter, Google Plus feeds for %s phone number in %s, %s. View the social reputation of ', $content->company, $content->city, $content->state, $content->company);
                                break;
                            case 'reports':
                                // Get Get Social Media Stats for Taqueria El Chino in New Rochelle, NY. View Facebook Likes and Twitter Followers for Taqueria El Chino
                                $content->meta_description = sprintf('Get Get Social Media Stats for %s in %s, %s. View Facebook Likes and Twitter Followers for %s', $content->company, $content->city, $content->state, $content->company);
                                break;
                            case 'directions':
                                // Get Directions to Taqueria El Chino in New Rochelle, NY.
                                $content->meta_description = sprintf('Get Directions to %s in %s, %s.', $content->company, $content->city, $content->state);
                                break;
                            case 'reviews':
                                // Get Taqueria El Chino Reviews in New Rochelle, NY. View Reputation and Feedback for Taqueria El Chino
                                $content->meta_description = sprintf('Get %s Reviews in %s, %s. View Reputation and Feedback for %s', $content->company, $content->city, $content->state, $content->company);
                                break;
                            case 'job':
                                // Get Taqueria El Chino Jobs in New Rochelle, NY. Job Opportunities for Taqueria El Chino
                                $content->meta_description = sprintf('Get %s Jobs in %s, %s. Job Opportunities for %s', $content->company, $content->city, $content->state, $content->company);
                                break;
                            case 'phone':
                                // Get the phone number 914-636-2197 for Taqueria El Chino in New Rochelle, NY.
                                $content->meta_description = sprintf('Get the phone number %s for %s in %s, %s.', $phone, $content->company, $content->city, $content->state);
                                break;
                        }
                    }
 
                    $bulk = $content->getUserBulkProfiles();
 
                    if ($bulk AND $bulk->is_a_phrase == "1")
                    {
                        $this->view->URL_region   = $region;
                        $this->view->URL_city     = $city;
                        $this->view->URL_category = $category;
 
                        $this->view->setVars(compact('content', 'categories', 'geodata_geocity', 'geodata_usstates',
                            'this_url', 'featured_businesses', 'type', 'bulk'));
 
                        $meta_tags   = [];
                        $meta_tags[] = '<meta name="description" content="' . $content->meta_description . '">';
                        $meta_tags[] = '<meta name="keywords" content="' . $content->meta_keywords . '"/>';
                        $meta_tags[] = '<meta name="revisit-after" content="1 days"/>';
                        $meta_tags[] = '<meta name="rating" content="general"/>';
                        $meta_tags[] = '<meta property="fb:app_id" content="1384347465125895" />';
                        $meta_tags[] = '<meta property="og:title" content="' . $content->meta_title . '" />';
                        $meta_tags[] = '<meta property="og:type" content="business.business" />';
                        $meta_tags[] =
                            '<meta property="og:url" content="' . BASE_URL . $this->router->getRewriteUri() . '" />';
                        $meta_tags[] = '<meta property="og:site_name" content="Find Us Local" />';
                        $meta_tags[] = '<meta property="og:description" content="' . $content->meta_description . '"/>';
                        $meta_tags[] =
                            '<meta property="og:image" content="//res.finduslocal.com/googlecache/' . $content->parentcategory_id . '/' . $content->category_id . '/' . $content->content_id . '.jpg"/>';
                        $meta_tags   = implode("\n", $meta_tags);
 
                        $this->view->META_TAGS = $meta_tags;
 
                        return $this->view->pick("index/profile/profile_phrase");
 
                    }
                    else
                    {
                        $meta_tags   = [];
                        $meta_tags[] = '<meta name="description" content="' . $content->meta_description . '">';
                        $meta_tags[] = '<meta name="keywords" content="' . $content->meta_keywords . '"/>';
                        $meta_tags[] = '<meta name="revisit-after" content="1 days"/>';
                        $meta_tags[] = '<meta name="rating" content="general"/>';
                        $meta_tags[] = '<meta property="fb:app_id" content="1384347465125895" />';
                        $meta_tags[] = '<meta property="og:title" content="' . $content->meta_title . '" />';
                        $meta_tags[] = '<meta property="og:type" content="business.business" />';
                        $meta_tags[] = '<meta property="og:url" content="' . BASE_URL . $this->router->getRewriteUri() . '" />';
                        $meta_tags[] = '<meta property="og:site_name" content="Find Us Local" />';
                        $meta_tags[] = '<meta property="og:description" content="' . $content->meta_description . '"/>';
                        $meta_tags[] =
                            '<meta property="og:image" content="//res.finduslocal.com/googlecache/' . $content->parentcategory_id . '/' . $content->category_id . '/' . $content->content_id . '.jpg"/>';
                        $meta_tags[] =
                            '<meta property="business:contact_data:street_address" content="' . $content->address . '" />';
                        $meta_tags[] =
                            '<meta property="business:contact_data:locality" content="' . $content->city . '"/>';
                        $meta_tags[] =
                            '<meta property="business:contact_data:region" content="' . $content->state . '"/>';
                        $meta_tags[] =
                            '<meta property="business:contact_data:postal_code" content="' . $content->zip . '" />';
                        $meta_tags[] = '<meta property="business:contact_data:country_name" content="US"/>';
                        $meta_tags[] = '<meta property="place:location:latitude" content="' . $content->lat . '" />';
                        $meta_tags[] = '<meta property="place:location:longitude" content="' . $content->lng . '" />';
                        $meta_tags   = implode("\n", $meta_tags);
 
                        $this->view->META_TAGS = $meta_tags;
 
                        $reviewcontainer = true;
 
                        $this->view->wallpaperbox =
                            $this->_getWallpaperBox($geodata_usstates->statecode, $geodata_geocity->city);
 
                        $this->view->jobsIndeed = $this->_getJob($categories->name, $geodata_geocity->postalCode);
 
 
                        $this->view->setVars(compact('content', 'categories', 'geodata_geocity', 'geodata_usstates',
                            'this_url', 'featured_businesses', 'type', 'reviewcontainer'));
 
                        return $this->view->pick("index/profile/profile_summary");
                    }
                }
            }
        }
 
        return $this->dispatcher->forward(array(
            "controller" => "index",
            "action" => "page404"
        ));
    }
 
    /**
     * @param $category_name
     * @param $zip
     *
     * @return array|string
     */
    protected function _getJob($category_name, $zip)
    {
        $jobsCodeHTML = [];
        $jobs_url     =
            "https://api.indeed.com/ads/apisearch?publisher=252009367554079&format=json&q=" . urlencode($category_name) . "&l=" . $zip . "&sort=&radius=&st=&jt=&start=&limit=5&fromage=&filter=&latlong=1&co=us&chnl=&userip=" . $_SERVER['REMOTE_ADDR'] . "&useragent=" . urlencode($_SERVER['HTTP_USER_AGENT']) . "&v=2";
 
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $jobs_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
 
        $result    = curl_exec($ch);
        $jobsArray = json_decode($result, true);
        if ($jobsArray)
        {
            foreach ($jobsArray['results'] as $job)
            {
                $jobsCodeHTML [] =
                    "<div id=\"job-entry\"><strong><span style=\"color:#000055;font-size:14px;\">{$job['company']}</span></strong><div style=\"padding-left:15px;font-size:12px;\"><strong>{$job['jobtitle']}</strong> in <strong>{$job['formattedLocation']}</strong><br>{$job['snippet']}<a href=\"{$job['url']}\" target=_blank rel=\"nofollow\">View Job and Apply</a></div><hr></div>";
            }
        }
        curl_close($ch);
        $jobsCodeHTML = implode("\n", $jobsCodeHTML);
 
        return $jobsCodeHTML;
    }
 
    /**
     * @return Response|\Phalcon\Http\ResponseInterface
     */
    public function removeAction()
    {
        $parentcategory_id = $this->dispatcher->getParam('parentcategory_id', 'int', null);
        $content_id        = $this->dispatcher->getParam('content_id', 'int', null);
        if (!$parentcategory_id OR !$content_id)
        {
            return $this->response->redirect('');
        }
        $confirmkey = $this->dispatcher->getParam('confirmkey', 'int', null);
        if ($confirmkey)
        {
            $removedb = RemovedBusinesses::findFirst([
                'parentcategory_id=:pid: AND content_id=:cid: AND confirmkey=:key: AND confirmed=0',
                'bind' => ['pid' => $parentcategory_id, 'cid' => $content_id, 'key' => $confirmkey]
            ]);
            if (!$removedb)
            {
                return $this->response->redirect('');
            }
            $removedb->confirmed = 1;
            if ($removedb->save())
            {
                die('Thank you - business profile has been removed');
            }
 
            return $this->response->redirect('');
 
        } else
        {
            if ($this->request->isPost())
            {
                $email  = $this->request->getPost('email', 'email', null);
                $reason = $this->request->getPost('reason', null, null);
                if ($email AND $reason)
                {
 
                    $removedb                    = new RemovedBusinesses();
                    $removedb->parentcategory_id = $parentcategory_id;
                    $removedb->content_id        = $content_id;
                    $removedb->ip_address        = $_SERVER['REMOTE_ADDR'];
                    $removedb->reason            = $reason;
                    $removedb->email             = $email;
                    $removedb->confirmed         = 0;
                    $removedb->confirmkey        = random_int(1111111, 9999999);
                    $remove_url                  =
                        BASE_URL . $this->router->getRewriteUri() . '/' . $removedb->confirmkey;
                    if ($removedb->save())
                    {
                        $mail = $this->mail;
                        $mail->addAddress($removedb->email);
                        $mail->isHTML(true);                                  // Set email format to HTML
                        $mail->Subject = 'FindUsLocal.com - Business Profile Removal Request';
                        $mail->Body    =
                            $this->view->getPartial('mail/html/removed_business', compact('remove_url'));
                        $mail->send();
                        die('Confirmation Email Has Been Sent!');
                    }
                }
            }
        }
 
 
    }
 
    /**
     * @param string $category
     * @param string $region
     * @param string $city
     * @param string $company
     * @param string $street
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View
     */
    public function job_opportunitiesAction($category, $region, $city, $company, $street = null)
    {
        return $this->summaryAction($category, $region, $city, $company, $street, 'job');
    }
 
    /**
     * @param string $category
     * @param null   $input_2
     * @param null   $input_3
     * @param null   $input_4
     *
     * @return View
     */
    public function profileAction($category, $input_2 = null, $input_3 = null, $input_4 = null)
    {
 
        //Get the state based on the users location (if outside of US or if State is null set default to NY)
        $userLocation = $this->locationServices->getIpLocation($this->request->getClientAddress());
 
        if (!is_object($userLocation))
        {
            $userLocation = json_decode($userLocation);
        }
 
        if (empty($userLocation->region) || empty($userLocation))
        {
            $userLocation->region = "NY";
        }
 
        $this->assets->collection('header')
            ->addCss('/css/profile_business-ful.css', false);
 
        //Category/currentpage
        if ($category && is_numeric($input_2) || $category && $input_2 == null)
        {
 
            $currentState = $this->locationServices->getStateViaCode($userLocation->region);
 
            //Get the ID for the category so we can add to the profile conditions below
            $categoryObject = $this->tag->getCategoryIdViaUrl($category);
 
            //Ensure input2 is set
            if (!$input_2 || $input_2 == null)
            {
                $input_2 = 1;
            }
 
            //Get the state based on the users location (if outside of US or if State is null set default to NY)
            $states = $this->locationServices->getStates();
 
            //Set the ofset for the pagination
            if ($input_2 == 1)
            {
                $offset = 0;
            } else
            {
                $offset = $input_2 * 10;
            }
 
            //Fetch the list of companies
            $profileModel = Content::find([
                'conditions' => 'state = ?1 AND category_id = ?2',
                "limit"      => 10,
                "offset"     => $offset,
                "bind"       => [
                    1 => $currentState->statecode,
                    2 => $categoryObject->id
                ]
            ]);
 
            $profileCount = Content::count([
                'conditions' => 'state = ?1 AND category_id = ?2',
                "bind"       => [
                    1 => $currentState->statecode,
                    2 => $categoryObject->id
                ]
            ]);
 
            //Return variables to model
            $this->view->setVars([
                "currentPage"        => $input_2,
                "stateSet"           => false,
                "page_url"           => $category,
                "companies"          => $profileModel,
                "resultsCount"       => $profileCount,
                "states"             => $states,
                "currentState"       => $currentState,
                "category"           => Categories::findFirst("url_id = '$category'"),
                "show_bottom_header" => true
            ]);
 
            $this->view->pick("index/category_listing");
 
        } //Category/State/CurrentPage
        else if ($category && is_string($input_2) && $input_3 == null || $category && is_string($input_2) && is_numeric($input_3))
        {
 
            //Get the ID for the category so we can add to the profile conditions below
            $categoryObject = $this->tag->getCategoryIdViaUrl($category);
 
            //Ensure input3 is set
            if (!$input_3 || $input_3 == null || $input_3 == "")
            {
                $input_3 = 1;
            }
 
            $states = $this->locationServices->getStates();
 
            $currentState = $this->locationServices->getStateViaUrl($input_2);
 
            if ($input_3 == 1)
            {
                $offset = 0;
            } else
            {
                $offset = $input_3 * 10;
            }
 
            //Fetch the list of companies
            $profileModel = Content::find([
                'conditions' => 'state = ?1 AND category_id = ?2',
                "limit"      => 10,
                "offset"     => $offset,
                "bind"       => [
                    1 => $currentState->statecode,
                    2 => $categoryObject->id
                ]
            ]);
 
            $profileCount = Content::count([
                'conditions' => 'state = ?1 AND category_id = ?2',
                "bind"       => [
                    1 => $currentState->statecode,
                    2 => $categoryObject->id
                ]
            ]);
 
            //Return variables to model
            $this->view->setVars([
                "currentPage"        => $input_3,
                "page_url"           => $category . "/" . $currentState->url_id,
                "stateSet"           => true,
                "companies"          => $profileModel,
                "resultsCount"       => $profileCount,
                "states"             => $states,
                "currentState"       => $currentState,
                "category"           => Categories::findFirst("url_id = '$category'"),
                "show_bottom_header" => true
            ]);
 
 
            $this->view->pick("index/category_listing");
 
        } else if ($category && is_string($input_2) && is_string($input_3) && is_string($input_4))
        {
            $this->view->pick("index/profile/profile_summary");
        }
 
    }
 
    /**
     * @return View
     */
    public function sitemapAction()
    {
        $states = GeodataUsstates::find([
            'order' => 'statecode'
        ]);
 
        $this->view->setVars(compact('states'));
    }
 
    /**
     * @param      $one_sign
     * @param null $page
     *
     * @return Response|\Phalcon\Http\ResponseInterface
     */
    public function sitemap_one_signAction($one_sign, $page = null)
    {
        // Remove duplicate pages
        if ($page == 1):
            return $this->response->redirect([
                'for'      => "frontend.sitemap_one_sign",
                'one_sign' => $one_sign
            ]);
        endif;
 
        if (is_null($page)):
            $page = 1;
        endif;
 
        $count_contents = 2089030; /* Content::count([
 
            'conditions' => 'company LIKE :company:',
            'bind'       => ['company' => $one_sign . '%']
        ]);*/
 
        $contents = Content::find([
            'conditions' => 'company LIKE :company: AND active = "1"',
            'bind'       => ['company' => $one_sign . '%'],
            'limit'      => $this->config->default->get('sitemap_per_page'),
            'offset'     => $page == 1 ? 0 : $page * $this->config->default->get('sitemap_per_page') - $this->config->default->get('sitemap_per_page')
        ]);
 
        $pages = $this->_pagination($contents, $count_contents, $page);
 
        //Return variables to model
        $this->view->setVars(compact('pages', 'one_sign', 'count_contents'));
 
    }
 
    /**
     * Get sitemap via state code
     *
     * @param      $state
     * @param null $page
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function sitemap_stateAction($state, $page)
    {
        // Remove duplicate pages
        if ($page == 1):
            return $this->response->redirect([
                'for'   => "frontend.sitemap_state",
                'state' => $state
            ]);
        endif;
 
        if (is_null($page)):
            $page = 1;
        endif;
 
        $contents = Content::find([
            'conditions' => 'state = :state: AND active = "1"',
            "bind"       => ['state' => $state],
            'limit'      => $this->config->default->get('sitemap_per_page'),
            'offset'     => $page == 1 ? 0 : $page * $this->config->default->get('sitemap_per_page') - $this->config->default->get('sitemap_per_page')
        ]);
 
        //Return variables to model
        $this->view->setVars(compact('contents'));
    }
 
    /**
     * @param $model
     * @param $number
     */
    public function sitemap_xmlAction()
    {
        $this->view->setRenderLevel(
            View::LEVEL_ACTION_VIEW
        );
        $this->response->setHeader('Content-Type', 'text/xml');
 
        $key_cache = 'sitemap-state-all';
 
        if ($this->frontCache->exists($key_cache))
        {
            $states = unserialize($this->frontCache->get($key_cache));
        } else
        {
            $states = GeodataUsstates::find([
                'order' => 'statecode'
            ]);
 
            $this->frontCache->save($key_cache, serialize($states));
        }
 
        $this->view->setVars(compact('states'));
 
    }
 
    /**
     * @param string $state
     */
    public function sitemap_state_xmlAction($state)
    {
        $this->response->setHeader('Content-Type', 'text/xml');
 
        $this->view->disable();
 
        $key_state = 'state-' . $state;
 
        $xml = '';
 
        if ($this->sitemapCache->exists($key_state))
        {
            $xml = $this->sitemapCache->get($key_state);
        } else
        {
            $key_cache = 'sitemap-state-' . strtolower($state) . '-count';
            $count_contents = 0;
            if ($this->frontCache->exists($key_cache))
            {
                $count_contents = $this->frontCache->get($key_cache);
            } else
            {
                $count_contents = Content::count([
                    'conditions' => 'state = :state:',
                    "bind"       => ['state' => $state]
                ]);
 
                $this->frontCache->save($key_cache, $count_contents);
            }
 
            if ($count_contents > 0)
            {
                $count_contents = ceil($count_contents/$this->config->default->get('sitemap_per_page'));
            }
 
            $xml = $this->view->getPartial('sitemap/sitemap_state_xml', compact('state', 'count_contents'));
 
            $this->sitemapCache->save($key_state, $xml);
        }
 
        echo $xml;
 
    }
 
    public function sitemap_state_page_xmlAction($state, $page)
    {
        $this->view->disable();
        $this->response->setHeader('Content-Type', 'text/xml');
 
        $key_state = $state . '/page-' . $page;
 
        if (!is_dir(ROOT_PATH . '/cache/sitemap/'  . $state))
        {
            mkdir(ROOT_PATH . '/cache/sitemap/'  . $state, 0755, true);
        }
 
        $xml = '';
 
        if ($this->sitemapCache->exists($key_state))
        {
            $xml = $this->sitemapCache->get($key_state);
        } else {
            $contents = Content::find([
                'conditions' => 'state = :state: AND active = "1"',
                "bind"       => ['state' => $state],
                'limit'      => $this->config->default->get('sitemap_per_page'),
                'offset'     => $page == 1 ? 0 : $page * $this->config->default->get('sitemap_per_page') - $this->config->default->get('sitemap_per_page')
            ]);
 
            $geodata_usstates = GeodataUsstates::findFirstByStatecode($state);
 
            $xml = $this->view->getPartial('sitemap/sitemap_state_page_xml', compact('contents', 'geodata_usstates'));
 
            $this->sitemapCache->save($key_state, $xml);
        }
 
        echo $xml;
 
    }
 
    /**
     * @param $model
     * @param $number
     */
    public function sitemap_xml_modelAction($model, $number)
    {
        $this->view->setRenderLevel(
            View::LEVEL_ACTION_VIEW
        );
        $this->response->setHeader('Content-Type', 'text/xml');
    }
 
    /**
     * Retrn contact page
     *
     * @link /contactus
     */
    public function contactusAction()
    {
        header_remove("X-Frame-Options");
        header_remove("X-Powered-By");
        header_remove("X-Content-Type-Options");
        $this->response->setHeader("X-Frame-Options", "DENY");
        header('X-Frame-Options: DENY');
        header('X-Frame-Options: GOFORIT') ;
    }
 
    /**
     * Return Terms of Use page
     *
     * @link /tos
     */
    public function tosAction()
    {
 
    }
 
    /**
     * Return Privacy page
     *
     * @link /privacy
     */
    public function privacyAction()
    {
 
    }
 
    /**
     * Get custom pagination
     *
     * @param object $contents
     * @param int    $count_contents
     * @param int    $page
     *
     * @return \stdClass
     */
    private function _pagination($contents, $count_contents, $page)
    {
        $pages                     = new \stdClass();
        $pages->items              = $contents;
        $pages->count_items        = count($contents);
        $pages->total_items        = $count_contents;
        $pages->current            = $page;
        $pages->total_pages        = (int)($count_contents / $this->config->default->get('sitemap_per_page'));
        $pages->companies_per_page = $this->config->default->get('sitemap_per_page');
        $pages->before             = $page == 1 ? 1 : $page - 1;
        $pages->next               = $page >= $pages->total_pages ? $pages->total_pages : $page + 1;
 
        return $pages;
    }
 
 
    /**
     * Get Wallpaper Box
     *
     * @param string $region (state)
     * @param string $city
     *
     * @return \stdClass or false
     */
    protected function _getWallpaperBox($region, $city)
    {
        $data                        = [];
        $data["CA"]["Los Angeles"]   = [
            "https://images.hdbackgroundpictures.com/t51b36e0d5186b86083.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_los-angeles.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_439203_los-angeles-hotels-millennium-biltmore-hotel-los-angeles-gallery.html"
        ];
        $data["TX"]["Dallas"]        = [
            "https://images.hdbackgroundpictures.com/t51ba77b61234790932.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_dallas.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_546742_dallas-at-dawn-texas-city-dallas-lights-texas-free-hd.html"
        ];
        $data["MA"]["Boston"]        = [
            "https://images.hdbackgroundpictures.com/t51b3dc3e8d3b981089.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_boston.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_191870_dance-parties-and-boston-s.html"
        ];
        $data["FL"]["Miami"]         = [
            "https://images.hdbackgroundpictures.com/t518bd04d0bcd097224.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_miami.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_442105_miami-city-at-night-florida-usa-globe-wallpapers.html"
        ];
        $data["IL"]["Chicago"]       = [
            "https://images.hdbackgroundpictures.com/t51b5b18a7604d20518.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_chicago.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_25819_chicago-boat-tour-illinois.html"
        ];
        $data["NY"]["New York"]      = [
            "https://images.hdbackgroundpictures.com/t51d77fe33462719215.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_new-york.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_558172_top-of-the-rock-new-york-city-sightseeing-usa-landscape.html"
        ];
        $data["GA"]["Atlanta"]       = [
            "https://images.hdbackgroundpictures.com/t518bd4dddd93485258.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_atlanta.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_56489_coast-night-scene-atlanta.html"
        ];
        $data["OR"]["Portland"]      = [
            "https://images.hdbackgroundpictures.com/t51b3dc4614ee886508.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_portland.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_442103_portland-city-oregon-united-states-usa-pictures.html"
        ];
        $data["PA"]["Philadelphia"]  = [
            "https://images.hdbackgroundpictures.com/t528ab0233810491645.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_Philiadelphia-skyline.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_568192_philadelphia-skyline-pennsylvania-united-states-usa-pictures.html"
        ];
        $data["CO"]["Denver"]        = [
            "https://images.hdbackgroundpictures.com/t518c5899b85ce46641.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_denver.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_58825_downtown-denver-night-united.html"
        ];
        $data["DC"]["Washington"]    = [
            "https://images.hdbackgroundpictures.com/t51b5e682702f861530.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_washington-dc.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_469614_neoclassical-architecture-white-house-washington-dc.html"
        ];
        $data["WA"]["Seattle"]       = [
            "https://images.hdbackgroundpictures.com/t517e17e540d5c91513.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_seattle.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_11875_etats-unis-seattle-seattle-001.html"
        ];
        $data["AZ"]["Phoenix"]       = [
            "https://images.hdbackgroundpictures.com/t51b2c4fcd618399070.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_phoenix.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_568320_phoenix-downtown-united-states-usa-pictures.html"
        ];
        $data["MO"]["St Louis"]      = [
            "https://images.hdbackgroundpictures.com/t51936dce12ef091254.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_St-Louis.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_99360_st-louis-arch-cities-hd.html"
        ];
        $data["FL"]["Tampa Bay"]     = [
            "https://images.hdbackgroundpictures.com/t51b1a2ac815a413339.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_Tampa-Bay.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_412199_water-and-skyline-tampa-bay-cities-city-lights-night-nite.html"
        ];
        $data["TX"]["Houston"]       = [
            "https://images.hdbackgroundpictures.com/t5284183c6909641258.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_houston.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_561943_twitter-houston-texans-texas-us-hd-high-definition-mobile.html"
        ];
        $data["CA"]["San Francisco"] = [
            "https://images.hdbackgroundpictures.com/t51889c63b645728598.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_san-francisco.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_55792_bay-bridge-san-francisco.html"
        ];
        $data["CA"]["San Diego"]     = [
            "https://images.hdbackgroundpictures.com/t519f3d147b3f192357.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_san-diego.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_203715_san-diego-city-night-light.html"
        ];
        $data["TX"]["San Antonio"]   = [
            "https://images.hdbackgroundpictures.com/t51a9662db369680925.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_san-antonio.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_339074_san-antonio-texas-usa.html"
        ];
        $data["MI"]["Detroit"]       = [
            "https://images.hdbackgroundpictures.com/t51b1a2b0432a319908.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_detroit.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_412205_detroit-cities-at-night-wallpapers-1024x768-pixel-city-hd.html"
        ];
        $data["NV"]["Las Vegas"]     = [
            "https://images.hdbackgroundpictures.com/t51b21fccae0c353424.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_las-vegas.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_320916_man-made-las-vegas-wallpaper.html"
        ];
        $data["OH"]["Cincinnati"]    = [
            "https://images.hdbackgroundpictures.com/t528ac4c97245712429.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_cincinnati.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_568996_cincinnati-kentucky-evening-wallpapers-is.html"
        ];
        $data["HI"]["Honolulu"]      = [
            "https://images.hdbackgroundpictures.com/t51a433289c7cb60340.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_honolulu_1.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_24135_honolulu-hawaii.html"
        ];
        $data["WI"]["Milwaukee"]     = [
            "https://images.hdbackgroundpictures.com/t528aca16dddaf84182.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_milwaukee.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_568895_unique-and-fun-things-to-do-in-milwaukee-wi-the-itinerary.html"
        ];
        $data["MD"]["Baltimore"]     = [
            "https://images.hdbackgroundpictures.com/t528acd122099150036.jpg",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_baltimore.html",
            "https://www.hdbackgroundpictures.com/pics/wallpapershd_568747_file-baltimore-inner-harbor-from-federal-hill-jpg-wikimedia-commons.html"
        ];
 
        if (array_key_exists($region, $data) AND array_key_exists($city, $data[$region]))
        {
 
            $phrases   = [];
            $phrases[] = "Download Free Background Pictures of {$city}, {$region}";
            $phrases[] = "Download Free Wallpaper Pics of {$city}, {$region}";
            $phrases[] = "Get Amazing {$city}, {$region} Background Pictures Free";
 
 
            $box                = new \stdClass();
            $box->phrase        = $phrases[array_rand($phrases)];
            $box->imageURL      = $data[$region][$city][2];
            $box->thumbImageURL = $data[$region][$city][0];
            $box->city          = $city;
            $box->region        = $region;
            $box->wpPage        = $data[$region][$city][1];
 
            return $box;
        }
 
        return false;
    }
 
    public function page404Action()
    {
 
        $this->response->setStatusCode(404, 'Not found');
 
        $this->assets->collection('header')
            ->addCss('/css/animate.css', false)
            ->addCss('/css/vegas.css', false)
            ->addCss('/css/error404.css', false);
    }
 
}
#16Apps\Frontend\Controllers\IndexController->beforeExecuteRoute(Object(Phalcon\Mvc\Dispatcher))
#17Phalcon\Dispatcher->dispatch()
#18Phalcon\Mvc\Application->handle()
/home/finduslocal/public_html/public/index.php (82)
<?php
/**
 * Ceated by Novnik Ltd.
 * User: artdevue - index.php
 * Date: 25.02.17
 * Time: 15:46
 * Project: phalcon-blank
 */
 
define('PHALCONSTART', microtime(true));
define('PROJECT_PATH', dirname(dirname(__FILE__)) . '/');
 
use Phalcon\Mvc\Application,
    Phalcon\Loader;
 
date_default_timezone_set('Europe/Dublin');
 
 
    require_once PROJECT_PATH . 'apps/bootstrap.php';
 
//    //debug
    if ($config->debug)
    {
        $debug = new \Phalcon\Debug();
        $debug->listen();
    } else
    {
        error_reporting(E_ALL);
    }
error_reporting(0);
 
    $loader = new Loader();
 
    $loader->registerNamespaces([
        'Apps\Commons\Models' => PROJECT_PATH . 'apps/commons/models/',
        'Library'             => PROJECT_PATH . 'library/'
    ]);
 
    $loader->registerClasses([
        'Apps\Commons\AbstractModule' => PROJECT_PATH . 'apps/commons/AbstractModule.php',
    ]);
 
    $loader->register();
 
    /**
     * Include services
     */
    require PROJECT_PATH . 'config/services.php';
    require PROJECT_PATH . 'config/repos.php';
 
    /**
     * Handle the request
     */
    $application = new Application();
 
    /**
     * Assign the DI
     *
     * @var Phalcon\DI\FactoryDefault $di
     */
    $application->setDI($di);
    //$application->useImplicitView(false);
 
    /**
     * Register application modules
     */
    $modules = [];
 
    foreach ($config->modules as $index => $modul)
    {
        $modules[$index] = [
            'className' => $modul->className,
            'path'      => $modul->dir . 'Module.php'
        ];
    }
 
    $application->registerModules($modules);
    //echo $application->handle()->getContent();
 
    require PROJECT_PATH . 'config/function.php';
 
    $response = $application->handle();
    $response->send();
KeyValue
_url/eating-places/new-york/cattaraugus
KeyValue
DOCUMENT_ROOT/home/finduslocal/public_html
GATEWAY_INTERFACECGI/1.1
HTTPSon
HTTP_ACCEPTtext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_ENCODINGgzip
HTTP_ACCEPT_LANGUAGEen-US,en;q=0.5
HTTP_CDN_LOOPcloudflare
HTTP_CF_CONNECTING_IP3.90.12.112
HTTP_CF_IPCOUNTRYUS
HTTP_CF_RAY4cb233ab9a24c1ea-IAD
HTTP_CF_VISITOR{"scheme":"https"}
HTTP_CONNECTIONKeep-Alive
HTTP_HOSTwww.finduslocal.com
HTTP_USER_AGENTCCBot/2.0 (https://commoncrawl.org/faq/)
HTTP_X_FORWARDED_FOR3.90.12.112
HTTP_X_FORWARDED_PROTOhttps
PATH/bin:/usr/bin
QUERY_STRING_url=/eating-places/new-york/cattaraugus
REDIRECT_HTTPSon
REDIRECT_QUERY_STRING_url=/eating-places/new-york/cattaraugus
REDIRECT_REDIRECT_HTTPSon
REDIRECT_REDIRECT_REDIRECT_HTTPSon
REDIRECT_REDIRECT_REDIRECT_STATUS200
REDIRECT_REDIRECT_REDIRECT_UNIQUE_IDXLzWaCZRgk8ACWqYMjUAAACM
REDIRECT_REDIRECT_STATUS200
REDIRECT_REDIRECT_UNIQUE_IDXLzWaCZRgk8ACWqYMjUAAACM
REDIRECT_STATUS200
REDIRECT_UNIQUE_IDXLzWaCZRgk8ACWqYMjUAAACM
REDIRECT_URL/index.php
REMOTE_ADDR3.90.12.112
REMOTE_PORT52222
REQUEST_METHODGET
REQUEST_URI/eating-places/new-york/cattaraugus
SCRIPT_FILENAME/home/finduslocal/public_html/public/index.php
SCRIPT_NAME/public/index.php
SERVER_ADDR38.81.130.87
SERVER_ADMIN[email protected]
SERVER_NAMEwww.finduslocal.com
SERVER_PORT80
SERVER_PROTOCOLHTTP/1.1
SERVER_SIGNATURE
SERVER_SOFTWAREApache
TZAmerica/Chicago
UNIQUE_IDXLzWaCZRgk8ACWqYMjUAAACM
PHP_SELF/public/index.php
REQUEST_TIME_FLOAT1555879528.3621
REQUEST_TIME1555879528
#Path
0/home/finduslocal/public_html/public/index.php
1/home/finduslocal/public_html/apps/bootstrap.php
2/home/finduslocal/public_html/vendor/autoload.php
3/home/finduslocal/public_html/vendor/composer/autoload_real.php
4/home/finduslocal/public_html/vendor/composer/ClassLoader.php
5/home/finduslocal/public_html/vendor/composer/autoload_static.php
6/home/finduslocal/public_html/vendor/symfony/polyfill-mbstring/bootstrap.php
7/home/finduslocal/public_html/vendor/symfony/polyfill-ctype/bootstrap.php
8/home/finduslocal/public_html/vendor/symfony/polyfill-php72/bootstrap.php
9/home/finduslocal/public_html/vendor/symfony/polyfill-php72/Php72.php
10/home/finduslocal/public_html/vendor/symfony/var-dumper/Resources/functions/dump.php
11/home/finduslocal/public_html/vendor/snowair/phalcon-debugbar/src/Debug.php
12/home/finduslocal/public_html/vendor/novnik-extensions-/phalcon-parse-rss/src/ParseRss.php
13/home/finduslocal/public_html/config/config.php
14/home/finduslocal/public_html/config/services.php
15/home/finduslocal/public_html/config/repos.php
16/home/finduslocal/public_html/config/function.php
17/home/finduslocal/public_html/apps/frontend/config/routes.php
18/home/finduslocal/public_html/apps/api/config/routes.php
19/home/finduslocal/public_html/apps/members/config/routes.php
20/home/finduslocal/public_html/apps/profile/config/routes.php
21/home/finduslocal/public_html/apps/oauth/config/routes.php
22/home/finduslocal/public_html/apps/frontend/Module.php
23/home/finduslocal/public_html/apps/commons/AbstractModule.php
24/home/finduslocal/public_html/apps/frontend/config/config.php
25/home/finduslocal/public_html/apps/frontend/controllers/IndexController.php
26/home/finduslocal/public_html/apps/frontend/controllers/BaseController.php
27/home/finduslocal/public_html/library/Auth/Auth.php
28/home/finduslocal/public_html/apps/commons/models/Users.php
Memory
Usage4194304