Phalcon Framework 3.3.1

Webzi\Exception: Not Found

/usr/local/php70/lib/php/Webzi/app/WebziFrontApplication.php (1080)
#0WebziFrontApplication->{closure}()
#1Phalcon\Mvc\Micro->handle()
/usr/local/php70/lib/php/Webzi/app/WebziFrontApplication.php (1090)
<?php
/******************************************************************************
 * Webzi Site Builder                                                         *
 *                                                                            *
 * Copyright (c) 2014-2017 Webzi Team                                         *
 * ************************************************************************** *
 * This is bundled with this package in the file LICENSE.txt                  *
 *                                                                            *
 * If you did not receive a copy of the license and are unable to             *
 * obtain it through the world-wide-web, please send an email                 *
 * to license@webzi.ir so we can send you a copy immediately.                 *
 * ************************************************************************** *
 * @Author   : Masoud Sabaghi <masoud.sabaghi@gmail.com>                         *
 * @Copyright: 2014-2017                                                      *
 ******************************************************************************/
 
include __DIR__ . '/AbstractApplication.php';
 
use Phalcon\Db\Column;
use Phalcon\Di;
use Phalcon\Filter;
use Phalcon\Forms\Element;
use Phalcon\Image;
use Phalcon\Mvc\Micro;
use Phalcon\Mvc\Model\Resultset;
use Phalcon\Validation\Validator;
use Solitweb\DirectAdmin\DirectAdmin;
use Webzi\Blog\Models\Category;
use Webzi\Blog\Models\Post;
use Webzi\Exception;
use Webzi\Forms\Form;
use Webzi\Helper\Binary;
use Webzi\Helper\File;
use Webzi\Helper\Html;
use Webzi\Helper\Text;
use Webzi\Image\Adapter\Imagick;
use Webzi\Models\Content;
use Webzi\Models\Option;
use Webzi\Models\Primary\Site;
use Webzi\Models\Taxonomy;
use Webzi\Models\TaxonomySeo;
use Webzi\Shop\Models\Attribute;
use Webzi\Shop\Models\Product;
use Webzi\Shop\Models\ProductAttribute;
use Webzi\Shop\Models\ProductMeta;
use Webzi\Template\Helper as TemplateRegistry;
 
/**
 * Class WebziFrontApplication
 */
class WebziFrontApplication extends AbstractApplication
{
    private $assets = [];
 
    /**
     * @param mixed $options
     *
     * @return void
     * @throws \Exception
     */
    public function run(array $options = [])
    {
        $environment = $options['environment']
            = isset($options['environment']) ? $options['environment'] : 'frontend';
 
        if ($environment !== 'install') {
            if (!isset($options['application']['publicDir']) || !isset($options['application']['baseUri'])) {
                return FALSE;
            }
 
 
            $options['application'] = array_merge($options['application'], [
                'viewsDir'  => $options['application']['publicDir'] . 'theme/',
                'uploadDir' => $options['application']['publicDir'] . 'uploads/',
                'uploadUri' => $options['application']['baseUri'] . 'uploads/'
            ]);
 
            if (!isset($options['application']['publicDir'])) {
                $options['application']['publicDir'] = $options['application']['publicDir'] . 'uploads/';
            }
            if (!isset($options['application']['uploadUri'])) {
                $options['application']['publicDir'] = $options['application']['baseUri'] . 'uploads/';
            }
        }
 
 
        parent::run($options);
        $application                   = new Micro();
        $application->config->compress = TRUE;
 
        $di = $this->_di;
        $di->setShared('app', $application);
        $application->setDI($di);
        $uri  = explode('/', $application->request->getURI());
        $path = $uri[1];
 
 
        if ($environment !== 'install' && $path !== 'install') {
 
            if (file_exists($di->get('config')->application->publicDir . 'theme/config/config.php')) {
                $config = require $di->get('config')->application->publicDir . 'theme/config/config.php';;
            } else {
                $config = [];
            }
        }
 
        if ($path === 'install' && $application->request->isGet()) {
            header('Access-Control-Allow-Origin: *');
 
            if ($environment === 'install') {
                echo json_encode(['server' => 'ok']);
            } else {
                echo json_encode(['server' => 'run']);
            }
 
            exit();
        }
 
 
        $application->get('/getScreenShot', function () use ($application) {
            $di       = $application->getDI();
            $option   = $di->get('option');
            $config   = $di->get('config');
            $response = $di->get('response');
            $request  = $di->get('request');
 
 
            $url = $config->application->baseUri;
 
 
            $lastUpodate      = $option->get('last_theme_update');
            $screenShotUpdate = $option->get('screen_shot_update');
            $screenFile       = $config->application->uploadDir . 'screen.jpg';
 
            if ($screenShotUpdate !== $lastUpodate || !file_exists($screenFile)) {
 
                $image = file_get_contents('http://webzi.cloudsite.ir/?url=' . $url);
                file_put_contents($screenFile, $image);
                $option->set('screen_shot_update', $lastUpodate, Option::AUTOLOAD_NONE);
            }
 
 
            if (!isset($image)) {
                $image = file_get_contents($screenFile);
            }
 
 
            header('Content-Type:image/jpeg');
            echo $image;
 
 
            exit();
        });
 
        if ($environment === 'install') {
 
 
            if (strstr($path, 'admin')) {
                $url      = 'https://webzi.ir/install';
                $userName = get_current_user();
 
 
                $site = Site::findFirst(
                    [
                        'conditions' => 'user_name=:user_name:',
                        'bind'       => [
                            'user_name' => $userName
                        ]
                    ]
                );
 
 
                $ip           = '94.182.110.234';
                $port         = '2842';
                $resellerUser = 'server1';
                $resellerPass = 'eb57e3795';
                $random       = $application->security->getRandom();
 
 
                $siteId   = str_replace('-', '', Binary::bin2uuid($site->getId()));
                $domain   = $site->getName() . '.' .
                    $application->config->application->tempDomain;
                $userName = $site->getUserName();
                $backend  = $site->getBackend();
                $dbPass   = $random->base64Safe(8);
 
 
                $daUser = new DirectAdmin();
                $daUser->connect($ip, $port);
                $daUser->set_login($resellerUser . '|' . $userName, $resellerPass);
                $daUser->set_method('POST');
                $daUser->query('/CMD_API_DATABASES', [
                    'action'  => 'modifyuser',
                    'domain'  => $domain,
                    'name'    => $userName . '_site',
                    'user'    => $userName . '_site',
                    'passwd'  => $dbPass,
                    'passwd2' => $dbPass,
                ]);
                $result = $daUser->fetch_parsed_body();
 
                if (!isset($result['error']) || !$result['error']) {
                    $fields_string = '';
                    $fields        = [
                        'test'     => '',
                        'email'    => '',
                        'mobile'   => '',
                        'userName' => $userName,
                        'dbPass'   => $dbPass,
                        'domain'   => $domain,
                        'siteId'   => $siteId,
                        'backend'  => $backend
                    ];
 
                    //url-ify the data for the POST
                    foreach ($fields as $key => $value) {
                        $fields_string .= $key . '=' . $value . '&';
                    }
                    rtrim($fields_string, '&');
 
                    //open connection
                    $ch = curl_init();
 
 
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                    //curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1000);
                    curl_setopt($ch, CURLOPT_POST, count($fields));
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                    curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
 
 
                    $content = curl_exec($ch);
 
 
                    //          if ($content === false) {
                    //                   throw new Exception(curl_error($ch), curl_errno($ch));
                    //}
 
                    curl_close($ch);
 
 
                    sleep(7);
 
                    $redirect = 'http://' . $domain . '/' . $backend . '/';
 
                    if ($application->request->hasQuery('token')) {
                        $redirect .= 'login-token?token=' . $application->request->get('token');
                    }
 
 
                    $application->response->redirect($redirect);
                    $application->response->send();
                    echo $application->response->getContent();
                }
 
 
            }
 
            exit();
 
 
            //            header('Access-Control-Allow-Origin: *');
            //            $publicDir = dirname($_SERVER["SCRIPT_FILENAME"]) . DIRECTORY_SEPARATOR;
            //
            //            if ($application->request->isPost()) {
            //                $sqlFile = $publicDir . 'install.sql';
            //
            //                if (!file_exists($sqlFile)) {
            //                    return FALSE;
            //                }
            //
            //
            //                $configFile = $publicDir . 'config.php';
            //                $siteConfig = File::getArray($configFile);
            //
            //                // DB
            //                $siteConfig['siteDatabase']['username'] = $application->request->getPost('dbUserName', 'string');
            //                $siteConfig['siteDatabase']['password'] = $application->request->getPost('dbPassword', 'string');
            //                $siteConfig['siteDatabase']['dbname']   = $application->request->getPost('dbName', 'string');
            //
            //                $application->config->siteDatabase->username = $siteConfig['siteDatabase']['username'];
            //                $application->config->siteDatabase->password = $siteConfig['siteDatabase']['password'];
            //                $application->config->siteDatabase->dbname   = $siteConfig['siteDatabase']['dbname'];
            //
            //                $check = $application->db->execute(file_get_contents(File::clearRelativePath($sqlFile)));
            //
            //                unlink($sqlFile);
            //
            //
            //                $siteConfig['application']['publicDir'] = $publicDir;
            //                $siteConfig['application']['uploadDir'] = $siteConfig['application']['publicDir'] . 'uploads/';
            //
            //                $domain = $application->request->getPost('domain', 'string');
            //
            //                $siteConfig['application']['baseUri']   = $domain . '/';
            //                $siteConfig['application']['uploadUri'] = $domain . '/uploads/';
            //                $siteConfig['application']['site']      = $application->request->getPost('siteId', 'string');
            //                $siteConfig['application']['backendPrefix']
            //                                                        = $application->request->getPost('backendPrefix', 'string');
            //
            //
            //                unset($siteConfig['environment']);
            //
            //                $random             = $application->security->getRandom();
            //                $siteConfig['keys'] = [
            //                    'cookie'         => str_replace('-', '', $random->uuid()),
            //                    'auth'           => str_replace('-', '', $random->uuid()),
            //                    'frontSession'   => str_replace('-', '', $random->uuid()),
            //                    'backendSession' => str_replace('-', '', $random->uuid())
            //                ];
            //
            //
            //                File::putArray($configFile, $siteConfig);
            //
            //                echo json_encode(['result' => 'success']);
            //
            //                exit();
            //            } else {
            //                echo json_encode(['server' => 'ok']);
            //                exit();
            //            }
        }
 
 
        if ($path === 'api') {
            $application->response->setHeader('Cache-Control', 'private, max-age=0, must-revalidate');
 
            $application->post(
                '/api/contact-us/{element:wze[0-9]+}',
                function ($element) use ($application, $config) {
 
                    $filter  = new Filter();
                    $contact = $application->request->getPost();
 
                    $form = new Form();
 
                    $field = new Element\Email('name');
                    $field->addValidator(new  Validator\PresenceOf());
                    $form->add($field);
 
                    $field = new Element\Email('email');
                    $field->addValidator(new  Validator\PresenceOf());
                    $field->addValidator(new  Validator\Email());
                    $form->add($field);
 
 
                    $field = new Element\Text('subject');
                    $form->add($field);
 
                    $field = new Element\TextArea('message');
                    $field->addValidator(new  Validator\PresenceOf());
                    $form->add($field);
 
                    if (!isset($config[$element])) {
                        return json_encode(['result' => 'failed']);
                    } else {
                        $setting = $config[$element];
                    }
 
 
                    if ($form->isValid($contact)) {
                        $name      = $filter->sanitize($contact['name'], 'string');
                        $mail      = $filter->sanitize($contact['email'], 'string');
                        $subject   = $filter->sanitize($contact['subject'], 'string');
                        $message   = $filter->sanitize($contact['message'], 'string');
                        $adminMail = isset($setting['email']) ? $filter->sanitize($setting['email'], 'string') : FALSE;
                        $secondAdminMail
                                   = isset($setting['secondMail']) ? $filter->sanitize($setting['secondMail'], 'string') : FALSE;
 
 
                        $to      = $adminMail;
                        $options = [];
                        //                        $options = [
                        //                            'from' => [
                        //                                'name'  => $name,
                        //                                'email' => $mail
                        //                            ]
                        //                        ];
                        if ($secondAdminMail) {
                            $options['cc'] = $secondAdminMail;
                        }
 
                        $message = 'نام: ' . $name . '<br>' . $message;
                        $message = 'ایمیل: ' . $mail . '<br>' . $message;
 
                        $this->getDi()->get('email')->send($adminMail, $subject, $message, $options);
 
                        //Todo complete mail
                        return json_encode(['result' => 'success']);
                    } else {
                        $messages = [];
                        foreach ($form->getMessages() as $message) {
                            $messages[$message->getField()] = $message->getMessage();
                        }
 
 
                        return json_encode(['result' => 'failed', 'messages' => $messages]);
                    }
                }
            );
 
 
            $application->map(
                '/api/{m:[a-zA-Z0-9\_\-]+}/{c:[a-zA-Z0-9\_\-]+}/{a:[a-zA-Z0-9\_\-]+}(/.*)*',
                function ($module, $controller, $action) use ($application) {
                    $module      = Text::camelize($module, '-');
                    $controller  = Text::camelize($controller, '-');
                    $modules     = $application->modulesManager->getModules();
                    $moduleNames = array_keys($modules);
                    $action      = Text::camelize($action);
 
                    if (in_array($module, $moduleNames, TRUE)) {
 
                        $moduleStartup = $application->getSharedService('Webzi\\' . $module . '\\Module');
                        $moduleStartup->setDI($application->getDI());
                        $moduleStartup->registerAutoloaders($application->getDI());
                        $moduleStartup->registerServices($application->getDI());
 
 
                        $application->dispatcher->setActionSuffix('');
                        $application->dispatcher->setControllerName($controller);
                        $application->dispatcher->setNamespaceName('Webzi\\' . $module . '\\Controllers\\Frontend\\');
                        $application->dispatcher->setActionName($action);
                        $application->dispatcher->setModuleName($module);
 
 
                        $params = $application->request->getQuery(NULL, 'string');
                        if (isset($params['_url'])) {
                            unset($params['_url']);
                        }
 
                        $application->dispatcher->setParams(
                            array_merge($application->dispatcher->getParams(), $params));
 
 
                        $application->dispatcher->dispatch();
                        $possibleResponse = $application->dispatcher->getReturnedValue();
 
 
                        if (is_bool($possibleResponse) && $possibleResponse === FALSE) {
                            $response = $application->response;
                        } else {
                            if (is_string($possibleResponse)) {
                                $response = $application->response;
                                $response->setContent($possibleResponse);
                            } else {
                                $response = $possibleResponse;
                            }
                        }
 
 
                        return $response;
                    }
                }
            )->via(
                [
                    'GET',
                    'POST',
                ]);
        } else {
 
            //            if (!$config) {
            //                if (!$application->config->get('is_published') && empty($path)) {
            //
            //                    $application->response->redirect($application->url->getBackendUrl())->send();
            //                    exit();
            //
            //                }
            //
            //            }
 
 
            $siteInfo = $application->option->getSiteInfo();
 
 
            if (isset($siteInfo['expire_date']) && time() - (60 * 60 * 72) > strtotime($siteInfo['expire_date'])) {
                $staticUri = $application->getDI()->get('config')->application->staticUri;
                $application->response->sendHeaders();
                $application->assets
                    ->collection('error')
                    ->addCss($application->url->get($staticUri . 'editor/css/base.css'));
                $application->view->setViewsDir($application->config->application->appDir . 'views/frontend/default/');
                echo $application->view->render('expire');
                exit();
            }
 
            // Add slash end of url
            if (!empty($path) && !preg_match('@\?.*|/{1}.*\..*|\#.*|/$@', $application->request->getURI())) {
                $application->response->redirect($application->url->getFullUrl() . '/', FALSE, 301)->send();
                exit();
            }
 
 
            $routers = isset($config['router']) ? $config['router'] : [];
            $hasShop = FALSE;
            foreach ($routers as $router => $pageConfig) {
                $routerPatterns = '/' . $di->get('filter')->sanitize(urlencode($router), 'url');
 
 
                if (array_key_exists('module', $pageConfig)) {
                    $module = $pageConfig['module'];
                    $type   = NULL;
                    if (array_key_exists('type', $pageConfig)) {
                        $type = $pageConfig['type'];
                    }
 
                    if ($module === 'blog') {
                        if ($type === 'blogRecent') {
                            $application->option->setTemporary('rewrite_url_blog_home', trim($routerPatterns, '/'));
                            $routerPatterns = [
                                $routerPatterns . '(/?page/)?{page:\d+}?',
                                '/' . $application->getDI()->get('option')
                                                  ->getUrLPattern('blog_tag', ['slug' => '{tag:[^/]+}']) . '(/?page/)?{page:\d+}?',
                                '/' . $application->getDI()->get('option')
                                                  ->getUrLPattern('blog_category', ['id' => '{category:\d+}', 'slug' => '{category_slug:[^/]+}']) . '(/?page/)?{page:\d+}?',
                                '/' . $application->getDI()->get('option')
                                                  ->getUrLPattern('blog_archive', ['date' => '{year:\d{4}}/{month:\d{2}}']) . '(/?page/)?{page:\d+}?'
                            ];
                        } else if ($type === 'blogSingle') {
                            $url = '/' . $application->getDI()->get('option')->getUrLPattern('blog_single',
                                    ['id' => '{id:\d+}', 'slug' => '([^\s!@^&*?.$\#\\/]+)', 'category' => '([^\s!@^&*?.$\#\\/]+)']);
 
                            $routerPatterns = [
                                $url,
                                strtolower($url)
                            ];
                        }
                    } else if ($module === 'shop') {
                        $hasShop = TRUE;
                        if ($type === 'shopRecent') {
                            $application->option->setTemporary('rewrite_url_shop_home', trim($routerPatterns, '/'));
                            $routerPatterns = [
                                $routerPatterns . '(/?page/)?{page:\d+}?',
                                '/' . $application->getDI()->get('option')
                                                  ->getUrLPattern('shop_tag', ['slug' => '{tag:[^/]+}']) . '(/?page/)?{page:\d+}?',
                                '/' . $application->getDI()->get('option')
                                                  ->getUrLPattern('shop_category', ['id' => '{category:\d+}', 'slug' => '{category_slug:[^/]+}']) . '(/?page/)?{page:\d+}?'
                            ];
                        } else if ($type === 'shopProduct') {
                            $url = '/' . $application->getDI()->get('option')->getUrLPattern('shop_single',
                                    ['id' => '{id:\d+}', 'slug' => '{slug:([^\s!@^&*?.$\#\\/]+)}', 'category' => '([^\s!@^&*?.$\#\\/]+)']);
 
                            $relativeUrl = '/' . $application->getDI()->get('option')->getUrLPattern('shop_single',
                                    ['id' => '{id:\d+}', 'slug' => '{slug:([^\s!@^&*?.$\#\\/]+)}', 'category' => '([^\s!@^&*?.$\#\\/]+)']);
 
 
                            $routerPatterns = [
                                $url,
                                strtolower($url)
                            ];
 
 
                        } else if ($type === 'shopCart') {
                            $application->response->setHeader('Cache-Control', 'private, max-age=0, must-revalidate');
 
                            $routerPatterns = [
                                'cart' => '/' . $application->getDI()->get('option')
                                                            ->getUrLPattern('shop_cart'),
 
                                'checkout' => '/' . $application->getDI()->get('option')
                                                                ->getUrLPattern('shop_checkout'),
 
                                'checkout_success' => '/' . $application->getDI()->get('option')
                                                                        ->getUrLPattern('shop_checkout_success'),
                            ];
                        }
                    }
                }
 
 
                if (is_string($routerPatterns)) {
                    $routerPatterns = (array)$routerPatterns;
                }
 
 
                foreach ($routerPatterns as $routerName => $routerPattern) {
 
                    $application
                        ->map(
                            $routerPattern,
                            function () use ($application, $pageConfig, $router, $routerName) {
 
 
                                $application->dispatcher->setParams(array_merge($application->router->getParams(), ['router' => $router . '/']));
 
                                if (!is_numeric($routerName)) {
                                    $application->dispatcher->setParam('router_name', $routerName);
                                }
 
 
                                //                            $application->assets->addMetaTag('ff', 'd');
 
 
                                $pageConfig['url'] = $application->url->getStaticBaseUri() . $router;
                                $pageConfig['url'] = trim($pageConfig['url'], '/') . '/';
                                $webzi             = new TemplateRegistry($pageConfig);
 
                                if (array_key_exists('module', $pageConfig)) {
                                    $webzi->{$pageConfig['module']}->init($pageConfig, $webzi);
                                }
 
 
                                $viewName = $pageConfig['id'];
                                unset($pageConfig, $router, $application);
 
 
                                /** @noinspection PhpParamsInspection */
                                echo Di::getDefault()->get('view')->render($viewName, ['webzi' => $webzi]);
                                Di::getDefault()->get('response')->send();
                            }
                        );
                }
            }
 
            if ($hasShop) {
                $application->get('/shop/compare/{ids:[/0-9]*}', function () use ($application) {
                    $di = $application->getDI();
 
                    $params = $di->get('router')->getParams();
 
                    if (empty($params['ids'])) {
                        throw new Exception('Not Found', '404');
                    }
 
                    $ids    = explode('/', $params['ids']);
                    $action = $this->modulesManager->getComponent('shop');
                    $ids    = array_slice($ids, 0, 8);   // first 8 items
 
 
                    $productsFetch = Product::find([
                        'columns'    => 'tbl.id , tbl.title, meta.price, thumbnail.path as thumbnail',
                        'joins'      => [
                            [ProductMeta::class, 'tbl.id=meta.product_id', 'meta', 'LEFT'],
                            'thumbnail' => [\Webzi\FileManager\models\File::class, 'thumbnail.id=tbl.thumbnail_id', 'thumbnail', 'LEFT'],
                        ],
                        'conditions' => 'tbl.id IN ({product_ids:array})',
                        'bind'       => ['product_ids' => $ids],
                    ]);
 
                    if ($productsFetch) {
                        $productsFetch = $productsFetch->toArray();
                    } else {
                        throw new Exception('Not Found', '404');
                    }
 
                    if (count($productsFetch) < 1) {
                        throw new Exception('Not Found', '404');
                    }
 
                    $products = [];
 
                    foreach ($productsFetch as $product) {
                        $product['attributes'] = [];
 
                        $product['price'] = $application->local->convertToLocalNumber((float)$product['price'], TRUE);
 
                        $product['thumbnail']
                            = $application->config->application->uploadUri . $product['thumbnail'];
 
                        $products[$product['id']] = $product;
                    }
 
 
                    $attributes      = [];
                    $attributesFetch = ProductAttribute::find([
                        'columns'    => ['product_id', 'attribute.id', 'attribute.name', 'tbl.group_id', 'tbl.value'],
                        'joins'      => [
                            [Attribute::class, 'attribute.id=tbl.attribute_id', 'attribute', 'LEFT'],
                        ],
                        'conditions' => ' product_id IN ({product_ids:array})',
                        'bind'       => ['product_ids' => $ids],
                        'order'      => 'tbl.position'
                    ]);
 
                    foreach ($attributesFetch as $attribute) {
                        if (empty($attributes[$attribute['id']])) {
                            $attributes[$attribute['id']] = $attribute['name'];
                        }
 
                        if (!empty($products[$attribute['product_id']])) {
                            $products[$attribute['product_id']]['attributes'][$attribute['id']] = $attribute['value'];
                        }
                    }
 
 
                    $application->dispatcher->setParams($application->router->getParams());
 
 
                    $application->view->setViewsDir($application->config->application->modulesDir . 'Shop/views/frontend/');
 
 
                    echo $application->view->render('compare', [
                        'products'   => $products,
                        'attributes' => $attributes,
                    ]);
                });
            }
        }
 
 
        $application->get('/robots.txt', function () use ($application) {
            $di = $application->getDI();
            $application->dispatcher->setParams($application->router->getParams());
 
            $application->view->setViewsDir($application->config->application->appDir . 'views/frontend/default/');
            $application->config->compress = FALSE;
 
            $application->response->setContentType('text/plain');
            $application->response->send();
 
 
            echo $application->view->render('robots');
        });
        $application->get('/site-map.xml', function () use ($application) {
            $di = $application->getDI();
 
            $application->dispatcher->setParams($application->router->getParams());
 
 
            $application->view->setViewsDir($application->config->application->appDir . 'views/frontend/default/');
            $application->config->compress = FALSE;
 
 
            $application->response->setContentType('application/xml');
            $application->response->send();
 
 
            $list        = [];
            $lastUpodate = $di->get('option')->get('last_theme_update', time());
            $lastUpodate = date('c', $lastUpodate);
 
 
            if (file_exists($di->get('config')->application->publicDir . 'theme/config/config.php')) {
                $config = require $di->get('config')->application->publicDir . 'theme/config/config.php';;
 
                if (!empty($config['router'])) {
                    foreach ($config['router'] as $name => $router) {
                        $index = !isset($router['noIndex']) || $router['noIndex'] === FALSE;
                        if (isset($router['permission']) && in_array($router['permission'], ['password', 'member'])) {
                            $index = FALSE;
                        }
                        $UUIDv4 = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i';
                        if (preg_match($UUIDv4, $name)) {
                            $index = FALSE;
                        }
 
                        if ($index) {
                            $list[] = [
                                'link'     => $application->url->getBaseUri() . $name,
                                'date'     => $lastUpodate,
                                'priority' => $name === '' ? '1' : '0.9',
                            ];
                        }
                    }
                }
            }
 
            $option = $application->getDI()->get('option');
 
            $categories = Taxonomy::find(
                [
                    'hydration'  => Resultset::HYDRATE_ARRAYS,
                    'conditions' => 'type IN ({types:array})',
                    'bind'       => ['types' => [\Webzi\Blog\Models\Category::TAXONOMY_TYPE, \Webzi\Shop\Models\Category::TAXONOMY_TYPE]]
                ]);
            if ($categories) {
                $categories = $categories->toArray();
            }
 
            $siteInfo      = $this->option->getSiteInfo();
            $plan          = isset($siteInfo['plan_en']) ? $siteInfo['plan_en'] : 'trial';
            $editorModules = [];
            $hasShop       = $plan !== 'company';
            $hasBlog       = $plan !== 'shop';
 
            foreach ($categories as $category) {
 
                $url = '';
                switch ($category['type']) {
                    case  \Webzi\Shop\Models\Category::TAXONOMY_TYPE:
                        if ($hasShop) {
                            $url = $option
                                ->getUrLPattern('shop_category',
                                    ['id'   => $category['id'],
                                     'slug' => $category['slug']]);
                            $url = $application->getDI()->get('config')->application->baseUri . $url . '/';
                        }
 
                        break;
 
                    case  \Webzi\Blog\Models\Category::TAXONOMY_TYPE:
                    default:
                        if ($hasBlog) {
                            $url = $option
                                ->getUrLPattern('blog_category',
                                    ['id'   => $category['id'],
                                     'slug' => $category['slug']]);
                            $url = $application->getDI()->get('config')->application->baseUri . $url . '/';
                        }
 
 
                        break;
                }
 
                $list[] = [
                    'link'     => $url,
                    'date'     => $lastUpodate,
                    'priority' => '0.7',
                ];
            }
 
 
            $contentList = Content::getList(
                [
                    'columns'    => 'taxonomy.slug AS caregory_slug, tbl.slug, tbl.id, tbl.type, tbl.modified_at',
                    'joins'      => [[Taxonomy::class, 'taxonomy.id=tbl.main_category', 'taxonomy', 'LEFT']],
                    'conditions' => 'tbl.status = :status: AND tbl.created_at < NOW()',
                    'bind'       => ['status' => '2'],
                    'bindTypes'  => ['status' => Column::BIND_PARAM_INT]
                ]
            );
 
 
            foreach ($contentList as $content) {
 
                if (in_array($content['type'], [Post::CONTENT_TYPE, Product::CONTENT_TYPE])) {
 
                    $url = '';
                    if (empty($content['caregory_slug'])) {
                        $content['caregory_slug'] = 'uncategorized';
                    }
                    switch ($content['type']) {
                        case  Product::CONTENT_TYPE:
                            if ($hasShop) {
                                $url = $option
                                    ->getUrLPattern('shop_single',
                                        ['id'   => $content['id'], 'category' => $content['caregory_slug'],
                                         'slug' => $content['slug']]);
                                $url = $application->getDI()->get('config')->application->baseUri . $url;
                            }
 
                            break;
 
                        case  Post::CONTENT_TYPE:
                        default:
                            if ($hasBlog) {
                                $url = $option
                                    ->getUrLPattern('blog_single',
                                        ['id'   => $content['id'], 'category' => $content['caregory_slug'],
                                         'slug' => $content['slug']]);
                                $url = $application->getDI()->get('config')->application->baseUri . $url;
                            }
 
                            break;
                    }
 
 
                    $list[] = [
                        'link'     => $url,
                        'date'     => date('c', strtotime($content['modified_at'])),
                        'priority' => '0.7',
                    ];
                }
            }
 
 
            echo $application->view->render('site-map', [
                'list' => $list,
            ]);
        });
 
 
        $routerPatterns = [
            '/blog/feed',
            '/blog/tag/{tag:[^/]+}/feed',
            '/blog/{category:\d+}-{category_slug:[^/]+}/feed',
            '/blog/{year:\d{4}}/{month:\d{2}}/feed',
        ];
 
        foreach ($routerPatterns as $routerPattern) {
            $application->get($routerPattern, function () use ($application) {
                $application->dispatcher->setParams($application->router->getParams());
 
                $action = $application->modulesManager->getComponent('blog');
 
                $posts = $action->getPosts(['pageSize' => '20', 'urlQuery' => TRUE,
                                            'local'    => FALSE, 'dateFormat' => 'D, d M Y H:i:s O']);
 
                //                echo json_encode($posts);
 
                $application->view->setViewsDir($application->config->application->appDir . 'views/frontend/default/');
 
 
                $application->response->setContentType('application/rss+xml');
                $application->response->send();
 
 
                echo $application->view->render('rss', [
                    'posts'  => $posts,
                    'option' => (object)[
                        'site_name'        => $application->getDI()->get('option')->get('site_name', ''),
                        'site_description' => $application->getDI()->get('option')->get('site_description', '')
                    ]]);
            });
        }
 
 
        $application->error(
            function ($exception) use ($application) {
                if ($application->config->debug !== TRUE) {
                    ob_clean();
 
                    if (0 === strpos($application->request->getURI(), '/api')) {
                        $application->response->setJsonContent(['status' => 'not_found'])->send();
 
                        exit();
                    }
 
                    $staticUri = $application->getDI()->get('config')->application->staticUri;
                    $application->response->setStatusCode(404, 'Not Found');
                    $application->response->sendHeaders();
                    $application->assets
                        ->collection('error')
                        ->addCss($application->url->get($staticUri . 'editor/css/base.css'));
                    $application->view->setViewsDir($application->config->application->appDir . 'views/frontend/default/');
                    echo $application->view->render('404');
                    exit();
                }
            }
        );
 
        $application->notFound(
 
 
            function () use ($application) {
 
                if (preg_match('/(?<fileName>[a-zA-Z0-9]{32})\.(?<options>[a-zA-Z0-9_,]*).(?<extension>[a-zA-Z0-9]{1,6})$/',
                        $application->request->getURI(), $matches) &&
                    ($fileName = isset($matches['fileName']) ? $matches['fileName'] : FALSE) &&
                    ($options = isset($matches['options']) ? $matches['options'] : FALSE) &&
                    ($extension = isset($matches['extension']) ? $matches['extension'] : FALSE) &&
                    is_file($file = $application->config->application->uploadDir .
                        File::clearRelativePath($fileName) . '.' . $extension)
 
                ) {
 
                    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
                        // if the browser has a cached version of this image, send 304
                        header('Last-Modified: ' . $_SERVER['HTTP_IF_MODIFIED_SINCE'], TRUE, 304);
                        exit;
                    }
 
 
                    $mineType    = mime_content_type($file);
                    $type        = current(explode('/', $mineType));
                    $options     = explode(',', $options);
                    $tempOptions = [];
                    foreach ($options as $option) {
                        $separate = explode('_', $option);
                        if (count($separate) === 2) {
                            $tempOptions[current($separate)] = next($separate);
                        }
                    }
                    $options = $tempOptions;
 
 
                    if ($type && $type === 'image' && isset($options['w']) && isset($options['h'])) {
 
 
                        $image     = new Imagick($file);
                        $imageSize = filesize($file);
 
 
                        $oldWidth     = $image->getWidth();
                        $oldHeight    = $image->getHeight();
                        $resizeWidth  = $width = (int)$options['w'];
                        $resizeHeight = $height = (int)$options['h'];
                        $resize       = isset($options['r']) ? $options['r'] : 'c';
                        $save         = isset($options['s']) ? $options['s'] : 'y';
 
 
                        if ($mineType === 'image/gif') {
                            $newFile = $fileName . '.w_' . $width . ',h_' .
                                $height . ',r_' . $resize . '.' . $extension;
                            if (copy($file, $application->config->application->uploadDir . $newFile)) {
 
 
                                $application->response->setHeader('Content-Type', $image->getMime());
                                $application->response->setContent(readfile($application->config->application->uploadUri . $newFile));
                                $application->response->send();
                                exit(); // Exit for prevent minifyHTML problem
 
                                //                                return $application->response->redirect($application->config->application->uploadUri . $newFile, FALSE, 301);
                            }
                        } else {
                            if ($oldWidth < $width) {
                                $resizeWidth  = $oldWidth;
                                $resizeHeight = $oldHeight;
                            }
 
 
                            // c=Crop, s=Stretch, k=Keep ratio
                            if ($resize === 'c') {
                                $image->cropToImage($resizeWidth, $resizeHeight);
                            } else {
                                if ($resize === 'k') {
                                    $image->resize($resizeWidth, $resizeHeight, Image::INVERSE);
                                } else {
                                    $image->resize($resizeWidth, $resizeHeight, Image::NONE);
                                }
                            }
 
 
                            $newFile
                                = $fileName . '.w_' . $width . ',h_' . $height . ',r_' . $resize . '.' . $extension;
 
 
                            if ($save === 'y') {
                                if ($image->save($application->config->application->uploadDir . $newFile, $imageSize > 154288 ? 80 : -1)) {
                                    $application->response->setHeader('Content-Type', $image->getMime());
                                    $application->response->setContent($image->render(NULL, $imageSize > 154288 ? 80 : 100));
                                    $application->response->send();
                                    exit(); // Exit for prevent minifyHTML problem
                                }
                            } else {
                                session_start();
                                //                                                                header('Cache-Control: private, max-age=10800, pre-check=10800');
                                //                                                                header('Pragma: private');
                                //                                                                header('Expires: ' . date(DATE_RFC822, strtotime(' 2 day')));
                                //                                header('Cache-Control: max-age=604800');
                                //                                header('Pragma: cache');
                                //                                header('Expires: ' . date(DATE_RFC822, strtotime(' 2 day')));
 
 
                                $application->response->setHeader('Cache-Control', 'max-age=604800');
                                $application->response->setHeader('Pragma', 'cache');
                                $application->response->setHeader('Expires', date(DATE_RFC822, strtotime(' 2 day')));
                                $application->response->setHeader('Content-Type', $image->getMime());
                                $application->response->setContent($image->render(NULL, $imageSize > 154288 ? 80 : 100));
                                $application->response->send();
 
                                exit(); // Exit for prevent minifyHTML problem
                            }
 
 
                        }
 
                    }
                } else {
 
                    if (!empty($application->config->wordpressCompatibility)) {
                        $slug    = trim(urldecode($application->request->getURI()), '/');
                        $content = Content::findFirstBySlug($slug);
                        if ($content) {
                            if ($content->getType() === Post::CONTENT_TYPE) {
                                $url = $application->url->getBaseUri() .
                                    $application->getDI()->get('option')
                                                ->getUrLPattern('blog_single',
                                                    ['id'   => $content->getId(), 'category' => 'uncategorized',
                                                     'slug' => $content->getSlug()]);
                            } else if ($content->getType() === Product::CONTENT_TYPE) {
                                $url = $application->url->getBaseUri() .
                                    $application->getDI()->get('option')
                                                ->getUrLPattern('shop_single',
                                                    ['id'   => $content->getId(), 'category' => 'uncategorized',
                                                     'slug' => $content->getSlug()]);
                            }
 
                            if ($url) {
                                $application->response->redirect($url, FALSE, 301);
                                $application->response->send();
                                exit(); // Exit for prevent minifyHTML problem
                            }
                        }
                    }
 
 
                    throw new Exception('Not Found', '404');
                }
 
 
            }
        );
 
 
        // Ob Buffer is needed for return response for front controllers
        ob_start();
        $application->handle();
        $content = ob_get_contents();
        ob_clean();
        $content = str_replace('[upload_uri]', $application->config->application->uploadUri, $content);
        $content = $application->tag->replaceBinds($content);
 
 
        if ($application->config->compress) {
            echo Html::minifyHTML($content);
        } else {
            echo $content;
        }
    }
 
}
#2WebziFrontApplication->run(Array([debug] => 1, [siteDatabase] => Array([username] => zoi_webzi, [password] => 4xaNhIunl8, [dbname] => zoi_webzi, [charset] => utf8mb4), [application] => Array(10), [mail] => Array([driver] => mail), [keys] => Array([cookie] => c638568ef7ba4468b5622e4872dce6788w, [auth] => c638568ef7ba4468b5622e4872dce6788z, [frontSession] => tJYZ8Rz8kpyoQgKnpAzZThZkelWhADUQ, [backendSession] => XKhHt2iWNts317IlBhaqrskIZAASCeuH), [environment] => frontend))
/usr/local/php70/lib/php/WebziFactory.php (47)
<?php
/******************************************************************************
 * Webzi Site Builder                                                         *
 *                                                                            *
 * Copyright (c) 2014-2017 Webzi Team                                         *
 * ************************************************************************** *
 * This is bundled with this package in the file LICENSE.txt                  *
 *                                                                            *
 * If you did not receive a copy of the license and are unable to             *
 * obtain it through the world-wide-web, please send an email                 *
 * to license@webzi.ir so we can send you a copy immediately.                 *
 * ************************************************************************** *
 * @Author: Masoud Sabaghi <masoud.sabaghi@gmail.com>                         *
 * @Copyright: 2014-2017                                                      *
 ******************************************************************************/
 
 
class WebziFactory
{
    public static function start(array $config = [])
    {
        $appPath = __DIR__ . '/Webzi/app';
 
        $uri  = explode('/', $_SERVER['REQUEST_URI']);
        $path = $uri[1];
 
        if (isset($config['application']['publicDir'])) {
            $config['application']['runtimeDir'] = $config['application']['publicDir'] . 'runtime/';
            $config['application']['cacheDir']   = $config['application']['publicDir'] . 'runtime/cache/';
            $config['application']['logDir']   = $config['application']['publicDir'] . 'runtime/logs/';
        }
 
        if ($path === '_debugbar' || (isset($config['application']['backendPrefix']) &&
                $path === $config['application']['backendPrefix'])) {
            require $appPath . '/WebziBackendApplication.php';
 
 
            (new WebziBackendApplication())->run($config);
        } else if ($path === 'job') {
            ignore_user_abort(TRUE);
            set_time_limit(0);
            require $appPath . '/WebziJobApplication.php';
            (new WebziJobApplication())->run($config);
        } else {
            require $appPath . '/WebziFrontApplication.php';
 
            (new WebziFrontApplication())->run($config);
        }
 
    }
}
#3WebziFactory::start(Array([debug] => 1, [siteDatabase] => Array([username] => zoi_webzi, [password] => 4xaNhIunl8, [dbname] => zoi_webzi, [charset] => utf8mb4), [application] => Array([publicDir] => /home/zoi/domains/zoi.ir/public_html/, [uploadDir] => /home/zoi/domains/zoi.ir/public_html/uploads/, [baseUri] => https://zoi.ir/, [uploadUri] => https://zoi.ir/uploads/, [site] => 88418ea03bf611e79a6d08002746f3a1, [backendPrefix] => admin3270rja8i, [runtimeDir] => /home/zoi/domains/zoi.ir/public_html/runtime/, [cacheDir] => /home/zoi/domains/zoi.ir/public_html/runtime/cache/, [logDir] => /home/zoi/domains/zoi.ir/public_html/runtime/logs/), [mail] => Array([driver] => mail), [keys] => Array([cookie] => c638568ef7ba4468b5622e4872dce6788w, [auth] => c638568ef7ba4468b5622e4872dce6788z, [frontSession] => tJYZ8Rz8kpyoQgKnpAzZThZkelWhADUQ, [backendSession] => XKhHt2iWNts317IlBhaqrskIZAASCeuH)))
/home/zoi/domains/zoi.ir/public_html/index.php (10)
<?php
 
 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
 
include "WebziFactory.php";
$config = require __DIR__ . '/config.php';
WebziFactory::start($config);
 
KeyValue
_url/<%- item.url %>
KeyValue
USERzoi
HOME/home/zoi
HTTP_ACCEPT_ENCODINGgzip
HTTP_CONNECTIONKeep-Alive
HTTP_HOSTzoi.ir
HTTP_ACCEPT_LANGUAGEen-US,en;q=0.5
HTTP_ACCEPTtext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_USER_AGENTCCBot/2.0 (https://commoncrawl.org/faq/)
SCRIPT_FILENAME/home/zoi/domains/zoi.ir/private_html/index.php
REDIRECT_STATUS200
SERVER_NAMEzoi.ir
SERVER_PORT443
SERVER_ADDR94.182.110.234
REMOTE_PORT40250
REMOTE_ADDR34.229.76.193
SERVER_SOFTWAREnginx/1.15.10
GATEWAY_INTERFACECGI/1.1
HTTPSon
REQUEST_SCHEMEhttps
SERVER_PROTOCOLHTTP/1.1
DOCUMENT_ROOT/home/zoi/domains/zoi.ir/private_html
DOCUMENT_URI/index.php
REQUEST_URI/%3C%25-%20item.url%20%25%3E
SCRIPT_NAME/index.php
CONTENT_LENGTH
CONTENT_TYPE
REQUEST_METHODGET
QUERY_STRING_url=/<%- item.url %>&
FCGI_ROLERESPONDER
PHP_SELF/index.php
REQUEST_TIME_FLOAT1558313345.1888
REQUEST_TIME1558313345
#Path
0/home/zoi/domains/zoi.ir/public_html/index.php
1/usr/local/php70/lib/php/WebziFactory.php
2/home/zoi/domains/zoi.ir/public_html/config.php
3/usr/local/php70/lib/php/Webzi/app/WebziFrontApplication.php
4/usr/local/php70/lib/php/Webzi/app/AbstractApplication.php
5/usr/local/php70/lib/php/Webzi/app/config/config.php
6/usr/local/php70/lib/php/Webzi/vendor/autoload.php
7/usr/local/php70/lib/php/Webzi/vendor/composer/autoload_real.php
8/usr/local/php70/lib/php/Webzi/vendor/composer/ClassLoader.php
9/usr/local/php70/lib/php/Webzi/vendor/composer/autoload_static.php
10/usr/local/php70/lib/php/Webzi/vendor/symfony/polyfill-mbstring/bootstrap.php
11/usr/local/php70/lib/php/Webzi/vendor/guzzlehttp/psr7/src/functions_include.php
12/usr/local/php70/lib/php/Webzi/vendor/guzzlehttp/psr7/src/functions.php
13/usr/local/php70/lib/php/Webzi/vendor/symfony/var-dumper/Resources/functions/dump.php
14/usr/local/php70/lib/php/Webzi/vendor/clue/stream-filter/src/functions.php
15/usr/local/php70/lib/php/Webzi/vendor/php-http/message/src/filters.php
16/usr/local/php70/lib/php/Webzi/vendor/paragonie/random_compat/lib/random.php
17/usr/local/php70/lib/php/Webzi/vendor/swiftmailer/swiftmailer/lib/swift_required.php
18/usr/local/php70/lib/php/Webzi/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php
19/usr/local/php70/lib/php/Webzi/vendor/psy/psysh/src/Psy/functions.php
20/usr/local/php70/lib/php/Webzi/vendor/myclabs/deep-copy/src/DeepCopy/deep_copy.php
21/usr/local/php70/lib/php/Webzi/vendor/ezyang/htmlpurifier/library/HTMLPurifier.composer.php
22/usr/local/php70/lib/php/Webzi/vendor/snowair/phalcon-debugbar/src/Debug.php
23/usr/local/php70/lib/php/Webzi/vendor/composer/autoload_namespaces.php
24/usr/local/php70/lib/php/Webzi/vendor/composer/autoload_psr4.php
25/usr/local/php70/lib/php/Webzi/vendor/composer/autoload_classmap.php
26/usr/local/php70/lib/php/Webzi/app/library/Services.php
27/usr/local/php70/lib/php/Webzi/app/Models/Option.php
28/usr/local/php70/lib/php/Webzi/app/Models/AbstractOption.php
29/usr/local/php70/lib/php/Webzi/app/library/Mvc/SiteModel.php
30/usr/local/php70/lib/php/Webzi/app/library/Helper/Text.php
31/usr/local/php70/lib/php/Webzi/app/library/Version.php
32/usr/local/php70/lib/php/Webzi/app/library/Http/Request.php
33/usr/local/php70/lib/php/Webzi/app/library/Mvc/Module/Manager.php
34/usr/local/php70/lib/php/Webzi/app/modules/Blog/Components/Setup.php
35/usr/local/php70/lib/php/Webzi/app/library/Mvc/Module/Setup.php
36/usr/local/php70/lib/php/Webzi/app/modules/Shop/Components/Setup.php
37/usr/local/php70/lib/php/Webzi/app/modules/Editor/Components/Setup.php
38/usr/local/php70/lib/php/Webzi/app/modules/FileManager/Components/Setup.php
39/usr/local/php70/lib/php/Webzi/app/modules/Customer/Components/Setup.php
40/home/zoi/domains/zoi.ir/public_html/theme/config/config.php
41/usr/local/php70/lib/php/Webzi/app/Models/Primary/Site.php
42/usr/local/php70/lib/php/Webzi/app/Models/Primary/AbstractSite.php
43/usr/local/php70/lib/php/Webzi/app/library/Mvc/Model/Behavior/UUID.php
44/usr/local/php70/lib/php/Webzi/vendor/solitweb/directadmin/src/DirectAdmin.php
45/usr/local/php70/lib/php/Webzi/app/library/Filter.php
Memory
Usage2097152