Example #1
0
 /**
  * Создание категории
  */
 public function edit($id)
 {
     if (!User::isAdmin()) {
         App::abort('403');
     }
     if (!($category = Category::find_by_id($id))) {
         App::abort('default', 'Категория не найдена!');
     }
     if (Request::isMethod('post')) {
         $category->token = Request::input('token', true);
         $category->parent_id = Request::input('parent_id');
         $category->name = Request::input('name');
         $category->slug = Request::input('slug');
         $category->description = Request::input('description');
         $category->sort = Request::input('sort');
         if ($category->save()) {
             App::setFlash('success', 'Категория успешно изменена!');
             App::redirect('/category');
         } else {
             App::setFlash('danger', $category->getErrors());
             App::setInput($_POST);
         }
     }
     $categories = Category::getAll();
     App::view('categories.edit', compact('category', 'categories'));
 }
Example #2
0
 /**
  * Метод вывода страницы с ошибками
  * @param  integer $code    код ошибки
  * @param  string  $message текст ошибки
  * @return string  сформированная страница с ошибкой
  */
 public static function abort($code, $message = '')
 {
     if ($code == 403) {
         header($_SERVER["SERVER_PROTOCOL"] . ' 403 Forbidden');
     }
     if ($code == 404) {
         header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
     }
     exit(App::view('errors.' . $code, compact('message')));
 }
Example #3
0
 /**
  * Handles exception/error and display them in a beautiful way
  *
  * @param array $trace
  */
 private function display(array $trace)
 {
     ob_end_clean();
     ob_start();
     $this->code = self::trace($this->line, $this->file);
     include 'templates/header.php';
     include 'templates/content.php';
     if (!empty($trace)) {
         foreach ($trace as $e) {
             $e = (object) $e;
             $this->message = '';
             $this->file = $e->file;
             $this->line = $e->line;
             $this->code = $this->trace($this->line, $this->file);
             $this->counter++;
             include 'templates/content.php';
         }
     }
     include 'templates/footer.php';
     ob_end_flush();
     \App::view()->setLayout(false);
     exit;
 }
Example #4
0
                App::view()->errormsg = _m('Distributive inconsistency!');
            } else {
                App::view()->ok = _m('List of files corresponds to the distributive');
            }
            break;
        case 2:
            // Сканируем на соответствие ранее созданному снимку
            $scanner->scan(true);
            if (count($scanner->whiteList) == 0) {
                App::view()->errormsg = _m('Snapshot image is not created');
            } else {
                if (count($scanner->modifiedFiles) || count($scanner->missingFiles) || count($scanner->newFiles)) {
                    App::view()->modifiedFiles = $scanner->modifiedFiles;
                    App::view()->missingFiles = $scanner->missingFiles;
                    App::view()->extraFiles = $scanner->newFiles;
                    App::view()->errormsg = _m('Snapshot inconsistency');
                } else {
                    App::view()->ok = _m('All files are consistent with previously made image');
                }
            }
            break;
        case 3:
            // Создаем снимок файлов
            $scanner->snap();
            App::view()->ok = _m('Snapshot successfully created');
            break;
    }
}
App::view()->form = $form->display();
App::view()->setTemplate('scanner.php');
Example #5
0
    }
    ksort($tpl_list);
    return $tpl_list;
}
$themes = getThemesList();
$act = filter_input(INPUT_GET, 'act', FILTER_SANITIZE_STRING);
$mod = filter_input(INPUT_GET, 'mod', FILTER_SANITIZE_STRING);
if ($act == 'set' && isset($themes[$mod])) {
    $theme = $themes[$mod];
    $description = '<br/><dl class="description">' . '<dt class="wide"><img src="' . $themes[$mod]['thumbinal'] . '" alt=""/></dt>' . '<dd>' . '<div class="header">' . $theme['name'] . '</div>' . (!empty($theme['author']) ? '<strong>' . _m('Author') . '</strong>: ' . htmlspecialchars($theme['author']) : '') . (!empty($theme['author_url']) ? '<br/><strong>' . _m('Site') . '</strong>: ' . htmlspecialchars($theme['author_url']) : '') . (!empty($theme['author_email']) ? '<br/><strong>Email</strong>: ' . htmlspecialchars($theme['author_email']) : '') . (!empty($theme['description']) ? '<br/><strong>' . _m('Description') . '</strong>: ' . htmlspecialchars($theme['description']) : '') . '</dd></dl>';
    $form = new Mobicms\Form\Form(['action' => App::request()->getUri()]);
    $form->title(_m('Choose Skin'))->html($description)->divider()->element('submit', 'submit', ['value' => _m('Choose'), 'class' => 'btn btn-primary'])->html('<a class="btn btn-link" href="../">' . _s('Back') . '</a>');
    if ($form->process() === true) {
        //        $stmt = App::db()->prepare("UPDATE `" . TP . "usr__users` SET `avatar` = ? WHERE `id` = " . App::user()->id);
        //        $stmt->execute([$image]);
        //        $stmt = null;
        //
        //        @unlink(FILES_PATH . 'users' . DS . 'avatar' . DS . Users::$data['id'] . '.jpg');
        //        @unlink(FILES_PATH . 'users' . DS . 'avatar' . DS . Users::$data['id'] . '.gif');
        //
        //        $form->continueLink = App::cfg()->sys->homeurl . 'profile/' . App::user()->id . '/option/avatar/';
        //        $form->successMessage = _d('avatar_applied');
        //        $form->confirmation = true;
        //        App::view()->hideuser = true;
    }
    App::view()->form = $form->display();
    App::view()->setTemplate('option_theme_set.php');
} else {
    App::view()->tpl_list = $themes;
    App::view()->setTemplate('option_theme.php');
}
Example #6
0
 * @license     LICENSE.md (see attached file)
 *
 * @module      IP WHOIS
 * @author      Oleg (AlkatraZ) Kasyanov <*****@*****.**>
 * @version     v.1.0.0 2015-02-01
 */
defined('MOBICMS') or die('Error: restricted access');
$form = new Mobicms\Form\Form(['action' => App::request()->getUri()]);
$form->infoMessages = false;
$query = App::router()->getQuery();
if (isset($query[0])) {
    $form->input['ip'] = $query[0];
    $form->isSubmitted = true;
    $form->isValid = true;
}
$form->title('IP WHOIS')->element('text', 'ip', ['label' => _s('IP address'), 'required' => true])->divider()->element('submit', 'submit', ['value' => _s('Search'), 'class' => 'btn btn-primary'])->html('<a class="btn btn-link" href="../">' . _s('Back') . '</a>');
//TODO: разобраться с обратной ссылкой
$form->validate('ip', 'ip');
if ($form->process() === true) {
    include_once __DIR__ . '/classes/WhoisClient.php';
    include_once __DIR__ . '/classes/Whois.php';
    include_once __DIR__ . '/classes/IpTools.php';
    $result = (new Whois())->lookup($form->output['ip']);
    $whois = nl2br(implode("\n", $result['rawdata']));
    // Выделяем цветом важные параметры
    $whois = strtr($whois, ['%' => '#', 'inetnum:' => '<span style="color: #c81237"><strong>inetnum:</strong></span>', 'netname:' => '<span style="color: #c81237"><strong>netname:</strong></span>', 'country:' => '<span style="color: #c81237"><strong>country:</strong></span>', 'route:' => '<span style="color: #c81237"><strong>route:</strong></span>', 'org-name:' => '<span style="color: #c81237"><strong>org-name:</strong></span>', 'descr:' => '<span style="color: #26a51d"><strong>descr:</strong></span>', 'address:' => '<span style="color: #26a51d"><strong>address:</strong></span>']);
    $form->divider()->html('<div class="alert alert-neytral"><small>' . $whois . '</small></div>');
}
App::view()->form = $form->display();
App::view()->setTemplate('index.php');
Example #7
0
 /**
  * Обратная связь
  */
 public function contact()
 {
     $request = Request::input('request');
     if (Request::isMethod('post')) {
         $email = Request::input('email');
         $name = Request::input('name');
         $message = Request::input('message');
         $captcha = Request::input('captcha');
         $errors = [];
         if (!App::isMail($email)) {
             $errors['email'] = 'Неверный формат адреса email';
         }
         if (!$name) {
             $errors['name'] = 'Небходимо заполнить имя отправителя';
         }
         if (!$message) {
             $errors['message'] = 'Необходимо заполнить текст сообщения';
         }
         if ($captcha != $_SESSION['captcha']) {
             $errors['captcha'] = 'Неверный проверочный код';
         }
         if (!$errors) {
             $message = nl2br(e($message));
             $to = [env('SITE_EMAIL') => env('SITE_ADMIN')];
             $subject = 'Новое письмо с сайта';
             $body = App::view('mailer.contact', compact('subject', 'message', 'request'), true);
             $headers['from'] = [$email => $name];
             // Отправка письма
             App::sendMail($to, $subject, $body, $headers);
             App::setFlash('success', 'Письмо успешно отправлено!');
             App::redirect('/');
         } else {
             App::setFlash('danger', $errors);
             App::setInput($_POST);
             App::redirect('/contact');
         }
     }
     App::view('pages.contact', compact('request'));
 }
Example #8
0
<?php

/*
 * mobiCMS Content Management System (http://mobicms.net)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://mobicms.net mobiCMS Project
 * @copyright   Copyright (C) mobiCMS Community
 * @license     LICENSE.md (see attached file)
 */
defined('MOBICMS') or die('Error: restricted access');
$homeUrl = App::request()->getBaseUrl();
$form = new Mobicms\Form\Form(['action' => App::request()->getUri()]);
$form->title(_s('Leave the site?'))->element('checkbox', 'clear', ['label_inline' => _s('Remove authorization from all devices')])->divider(12)->element('submit', 'submit', ['value' => '   ' . _s('Exit') . '   ', 'class' => 'btn btn-primary btn-lg btn-block'])->html('<br/><a class="btn btn-default btn-lg btn-block" href="' . $homeUrl . '/profile/' . App::user()->get()->id . '/">' . _s('Back') . '</a>');
if ($form->process() === true) {
    App::user()->logout($form->output['clear']);
    App::redirect($homeUrl);
}
App::view()->form = $form->display();
App::view()->setTemplate('login.php');
Example #9
0
<?php

/**
 * mobiCMS Content Management System (http://mobicms.net)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://mobicms.net mobiCMS Project
 * @copyright   Copyright (C) mobiCMS Community
 * @license     LICENSE.md (see attached file)
 */
defined('MOBICMS') or die('Error: restricted access');
//TODO: переделать счетчик на тех, у кого уже регистрация подтверждена
App::view()->total = App::db()->query("SELECT COUNT(*) FROM `usr__users` ")->fetchColumn();
App::view()->list = App::db()->query("\n    SELECT *\n    FROM `usr__users`\n    ORDER BY `id` ASC" . App::db()->pagination())->fetchAll();
App::view()->setTemplate('user_list.php');
Example #10
0
 /**
  * Ответ на сообщение для администрации
  */
 public function reply($id)
 {
     if (!User::isAdmin()) {
         App::abort(403);
     }
     if (!($guest = Guestbook::find_by_id($id))) {
         App::abort('default', 'Сообщение не найдено!');
     }
     if (Request::isMethod('post')) {
         $guest->scenario = 'reply';
         $guest->token = Request::input('token', true);
         $guest->reply = Request::input('text');
         if ($guest->save()) {
             App::setFlash('success', 'Ответ успешно добавлен!');
             App::redirect('/guestbook');
         } else {
             App::setFlash('danger', $guest->getErrors());
             App::setInput($_POST);
         }
     }
     App::view('guestbook.reply', compact('guest'));
 }
Example #11
0
<?php

/**
 * mobiCMS Content Management System (http://mobicms.net)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://mobicms.net mobiCMS Project
 * @copyright   Copyright (C) mobiCMS Community
 * @license     LICENSE.md (see attached file)
 */
defined('MOBICMS') or die('Error: restricted access');
App::view()->total = App::db()->query("SELECT COUNT(*) FROM `system__sessions` WHERE `user_id` = 0 AND `timestamp`  > " . (time() - 300))->fetchColumn();
if (App::view()->total) {
    App::view()->list = App::db()->query("\n        SELECT\n            `user_id` AS `id`,\n            `timestamp` AS `last_visit`,\n            `ip`,\n            `ip_via_proxy`,\n            `user_agent`,\n            `place`,\n            `views`,\n            `movings`\n        FROM\n            `system__sessions`\n        WHERE\n            `user_id` = 0 AND `timestamp`  > " . (time() - 300) . "\n        ORDER BY\n            `views` DESC" . App::db()->pagination())->fetchAll();
}
App::view()->setTemplate('guests.php');
Example #12
0
        $form->successMessage = _g('Avatar is installed');
        $form->confirmation = true;
        App::view()->hideuser = true;
    }
    App::view()->form = $form->display();
    App::view()->setTemplate('avatars_set.php');
} elseif (isset($query[1], $query[2], $catalog[$query[2]]) && $query[1] == 'list') {
    // Показываем список аватаров в выбранной категории
    $avatars = glob(ROOT_PATH . 'assets' . DS . 'avatars' . DS . $query[2] . DS . '*.{gif,jpg,png}', GLOB_BRACE);
    App::view()->total = count($avatars);
    App::view()->start = App::vars()->page * App::view()->pagesize - App::view()->pagesize;
    $end = App::vars()->page * App::view()->pagesize;
    if ($end > App::view()->total) {
        $end = App::view()->total;
    }
    if (App::view()->total) {
        App::view()->list = [];
        for ($i = App::view()->start; $i < $end; $i++) {
            App::view()->list[$i] = ['image' => $homeUrl . '/assets/avatars/' . urlencode($query[2]) . '/' . basename($avatars[$i]), 'link' => App::user()->isValid() ? '../../set/' . urlencode($query[2]) . '/' . urlencode(basename($avatars[$i])) : '#'];
        }
    }
    App::view()->cat = $query[2];
    App::view()->setTemplate('avatars_list.php');
} else {
    // Показываем каталог аватаров (список категорий)
    App::view()->list = [];
    foreach ($catalog as $key => $val) {
        App::view()->list[] = ['link' => $uri . 'list/' . urlencode($key) . '/', 'name' => $val, 'count' => count(glob(ROOT_PATH . 'assets' . DS . 'avatars' . DS . $key . DS . '*.{gif,jpg,png}', GLOB_BRACE))];
    }
    App::view()->setTemplate('avatars_index.php');
}
Example #13
0
<?php

/*
 * mobiCMS Content Management System (http://mobicms.net)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://mobicms.net mobiCMS Project
 * @copyright   Copyright (C) mobiCMS Community
 * @license     LICENSE.md (see attached file)
 */
defined('MOBICMS') or die('Error: restricted access');
// Показываем меню настроек
App::view()->setTemplate('option.php');
Example #14
0
 /**
  * 获取视图组件对象
  *
  * @return View\View
  */
 public function getView()
 {
     empty($this->view) and $this->view = $this->app->view();
     return $this->view;
 }
Example #15
0
<?php

/*
 * mobiCMS Content Management System (http://mobicms.net)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://mobicms.net mobiCMS Project
 * @copyright   Copyright (C) mobiCMS Community
 * @license     LICENSE.md (see attached file)
 */
defined('MOBICMS') or die('Error: restricted access');
// Построение графика репутации
$reputation = !empty(App::profile()->reputation) ? unserialize(App::profile()->reputation) : ['a' => 0, 'b' => 0, 'c' => 0, 'd' => 0, 'e' => 0];
App::view()->reputation = [];
App::view()->reputation_total = array_sum($reputation);
foreach ($reputation as $key => $val) {
    App::view()->reputation[$key] = App::view()->reputation_total ? 100 / App::view()->reputation_total * $val : 0;
}
App::view()->setTemplate('profile.php');
Example #16
0
 public function setLanguage($iso)
 {
     if (is_file(ROOT_PATH . 'assets' . DS . 'js' . DS . 'sceditor' . DS . $iso[0] . '.js')) {
         \App::view()->embedJs('<script src="' . \App::request()->getBaseUrl() . '/assets/js/sceditor/' . $iso[0] . '.js" type="text/javascript"></script>');
     }
 }
Example #17
0
<?php

/*
 * mobiCMS Content Management System (http://mobicms.net)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://mobicms.net mobiCMS Project
 * @copyright   Copyright (C) mobiCMS Community
 * @license     LICENSE.md (see attached file)
 */
defined('MOBICMS') or die('Error: restricted access');
App::view()->setTemplate('option_avatar.php');
Example #18
0
<?php

/*
 * mobiCMS Content Management System (http://mobicms.net)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://mobicms.net mobiCMS Project
 * @copyright   Copyright (C) mobiCMS Community
 * @license     LICENSE.md (see attached file)
 *
 * @module      Registration
 * @author      Oleg (AlkatraZ) Kasyanov <*****@*****.**>
 * @version     v.1.0.0 2015-02-01
 */
defined('MOBICMS') or die('Error: restricted access');
if (App::user()->isValid()) {
    App::view()->setTemplate('registered.php');
} else {
    require_once __DIR__ . '/includes/' . 'registration.php';
}
Example #19
0
 /**
  * RSS лента
  */
 public function rss()
 {
     $news_list = News::all(['limit' => 15, 'order' => 'created_at desc', 'include' => ['user']]);
     header("Content-type:application/rss+xml; charset=utf-8");
     App::view('news.rss', compact('news_list'));
 }
Example #20
0
            $writeStmt = $db->prepare('UPDATE `user__reputation` SET `value` = ? WHERE `from` = ? AND `to` = ?');
        } else {
            $writeStmt = $db->prepare('INSERT INTO `user__reputation` SET `value` = ?, `from` = ?, `to` = ?');
        }
        $writeStmt->execute([$form->output['vote'], $user->id, $profile->id]);
        // Обновляем кэш пользователя
        $repStmt = $db->prepare('
            SELECT
            COUNT(IF(`value` =  2, 1, NULL)) AS `a`,
            COUNT(IF(`value` =  1, 1, NULL)) AS `b`,
            COUNT(IF(`value` =  0, 1, NULL)) AS `c`,
            COUNT(IF(`value` = -1, 1, NULL)) AS `d`,
            COUNT(IF(`value` = -2, 1, NULL)) AS `e`
            FROM `user__reputation`
            WHERE `to` = ?
        ');
        $repStmt->execute([$profile->id]);
        $reputation = $repStmt->fetch();
        $profile->reputation = serialize($reputation);
        $profile->save();
    }
    App::view()->form = $form->display();
}
App::view()->counters = $reputation;
App::view()->reputation = [];
App::view()->reputation_total = array_sum($reputation);
foreach ($reputation as $key => $val) {
    App::view()->reputation[$key] = App::view()->reputation_total ? 100 / App::view()->reputation_total * $val : 0;
}
App::view()->setTemplate('reputation.php');
Example #21
0
    $cache = [];
    $smilies = glob(ROOT_PATH . 'assets' . DS . 'smilies' . DS . '*' . DS . '*.{gif,jpg,png}', GLOB_BRACE);
    foreach ($smilies as $val) {
        $file = basename($val);
        $name = explode(".", $file);
        $parent = basename(dirname($val));
        $image = '<img src="' . App::request()->getBaseUrl() . 'assets/smilies/' . $parent . '/' . $file . '" alt="" />';
        if ($parent == '_admin') {
            $cache['adm_s'][] = '/:' . preg_quote($name[0]) . ':/';
            $cache['adm_r'][] = $image;
            $cache['adm_s'][] = '/:' . preg_quote(Includes\Functions::translit($name[0])) . ':/';
            $cache['adm_r'][] = $image;
        } elseif ($parent == '_simply') {
            $cache['usr_s'][] = '/:' . preg_quote($name[0]) . '/';
            $cache['usr_r'][] = $image;
        } else {
            $cache['usr_s'][] = '/:' . preg_quote($name[0]) . ':/';
            $cache['usr_r'][] = $image;
            $cache['usr_s'][] = '/:' . preg_quote(Includes\Functions::translit($name[0])) . ':/';
            $cache['usr_r'][] = $image;
        }
    }
    if (file_put_contents(CACHE_PATH . 'smilies.cache', serialize($cache))) {
        App::view()->save = _dg('The cache is updated');
    } else {
        App::view()->error = _dg('When updating a cache there was a error');
    }
}
App::view()->form = $form->display();
App::view()->setTemplate('smilies.php');
Example #22
0
$homeUrl = App::request()->getBaseUrl();
$rssCacheFile = CACHE_PATH . 'rss-feed.cache';
// Cache file
$rssCacheTime = 600;
// Cache Time in seconds
// Read the RSS feed from the database and write cache
if (!is_file($rssCacheFile) || filemtime($rssCacheFile) < time() - $rssCacheTime) {
    $rss = ['<rss version="2.0">', '<channel>', '<title>' . htmlspecialchars(Config::$copyright) . '</title>', '<link>' . $homeUrl . '</link>', '<description>Site news</description>', '<language>ru-ru</language>', '<pubDate>' . date("D, j M Y G:i:s", time()) . ' GMT' . '</pubDate>', '<lastBuildDate>' . date("D, j M Y G:i:s", time()) . ' GMT' . '</lastBuildDate>', '<docs>http://blogs.law.harvard.edu/tech/rss</docs>', '<generator>mobiCMS http://mobicms.net</generator>', '<webMaster>' . Config::$email . '</webMaster>'];
    $query = App::db()->query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 15");
    while ($result = $query->fetch()) {
        $rss[] = '<item>';
        $rss[] = '<title><![CDATA[' . strip_tags(trim($result['title'])) . ']]></title>';
        $rss[] = '<link>' . $homeUrl . '/news/' . '</link>';
        $rss[] = '<description><![CDATA[' . strip_tags(trim($result['text'])) . ']]></description>';
        $rss[] = '<pubDate>' . date("D, j M Y G:i:s", $result['time']) . ' GMT' . '</pubDate>';
        $rss[] = '<guid>' . $homeUrl . '/news/' . '</guid>';
        $rss[] = '</item>';
    }
    $rss[] = '</channel>';
    $rss[] = '</rss>';
    // Write RSS cache
    if (file_put_contents($rssCacheFile, implode("\n", $rss)) === false) {
        throw new RuntimeException('Can not write RSS cache file');
    }
}
// Display RSS feed
ob_end_clean();
App::view()->setLayout(false);
header('Content-type: text/xml; charset="utf-8"');
echo '<?xml version="1.0" encoding="utf-8"?>' . "\n";
readfile($rssCacheFile);
Example #23
0
    $app->setConfig($config);
    // Set up app directories.
    $app->setDirectories(__DIR__);
} catch (\Exception $e) {
    ldd($e->getMessage());
}
// Set up app templates.
$app->setConfig(['app.templates.default.file' => TemplateDefaults::DEFAULT_NAME, 'app.templates.default.content' => TemplateDefaults::DEFAULT_CONTENT, 'app.templates.error404.file' => TemplateDefaults::ERROR404_NAME, 'app.templates.error404.content' => TemplateDefaults::ERROR404_CONTENT, 'app.templates.error500.file' => TemplateDefaults::ERROR500_NAME, 'app.templates.error500.content' => TemplateDefaults::ERROR500_CONTENT]);
// Set up the Twig environment.
$loaderFS = new \Twig_Loader_Filesystem($app->get('app.dir.templates'));
$loaderArray = new \Twig_Loader_Array([$app->get('app.templates.default.file') => $app->get('app.templates.default.content'), $app->get('app.templates.error404.file') => $app->get('app.templates.error404.content'), $app->get('app.templates.error500.file') => $app->get('app.templates.error500.content')]);
$loader = new \Twig_Loader_Chain([$loaderFS, $loaderArray]);
$config = ['cache' => $app->get('app.dir.cache.templates'), 'debug' => $app->get('app.settings.debug')];
// Register Twig as the view library.
$app->register('view', '\\Twig_Environment', [$loader, $config]);
$app->view()->addGlobal('insert', new \Bluematt\Korpus\DocumentInserter($app->get('app.dir.pages')));
// Handle all routes.
$app->route('GET *', function () use($app) {
    try {
        // Get the route.
        $app->initRoute();
        $document = (new DocumentLocator($app->get('app.dir.pages')))->fromRoute($app->get('app.route.path'));
        // Work out if the document has expired and should not redirect.
        if ($document->hasExpired() && !$document->shouldRedirect()) {
            throw new Exceptions\DocumentExpiredException($app->get('app.route'));
        }
        // If the document should redirect, then redirect it.
        if ($document->shouldRedirect()) {
            $app->redirect($document->redirect);
        }
        // Render the document.
Example #24
0
<?php

/**
 * mobiCMS Content Management System (http://mobicms.net)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://mobicms.net mobiCMS Project
 * @copyright   Copyright (C) mobiCMS Community
 * @license     LICENSE.md (see attached file)
 */
defined('MOBICMS') or die('Error: restricted access');
$file = ROOT_PATH . 'system/logs/ip-requests.log';
$array = [];
if (is_file($file)) {
    $array = file($file);
    // Убираем заголовок текстового файла
    unset($array[0], $array[1]);
    // Передаем в шаблон 100 самых активных адресов
    App::view()->list = array_slice($array, 0, 100);
}
$total = count($array);
App::view()->total = $total > 100 ? '> 100' : $total;
App::view()->setTemplate('ip.php');
Example #25
0
 * @param string $domain
 * @return string
 */
function _m($message, $domain = 'default')
{
    global $i18n;
    return $i18n->translateModule($message, $domain);
}
/**
 * Plural version of _m()
 *
 * @param string      $singular
 * @param string      $plural
 * @param string      $count
 * @param null|string $domain
 * @return string
 */
function _mp($singular, $plural, $count, $domain = 'default')
{
    global $i18n;
    return $i18n->translateModulePlural($singular, $plural, $count, $domain);
}
// Output buffering
ob_start();
// Shutdown handlers
register_shutdown_function(function () use($request, $response) {
    $response->setContent(App::view()->render());
    $response->prepare($request)->send();
    session_register_shutdown();
    // This important!
});
Example #26
0
 /**
  * @covers \Phix\App::render
  * @covers \Phix\App::renderer
  */
 public function testRender()
 {
     $app = new App();
     $app->viewsDir(dirname(__FILE__) . '/_files/views');
     $content = $app->render(function ($app, array $vars, $format) {
         return 'foo';
     }, array(), 'html');
     $this->assertEquals('foo', $app->output());
     $this->assertTrue(in_array('Content-Type: text/html;charset=utf-8', $app->headers()));
     $app->reset();
     $app->render('view', array('controller' => 'foo'), function () {
         return 'html';
     });
     $this->assertEquals('foo', $app->output());
     $this->assertTrue(in_array('Content-Type: text/html;charset=utf-8', $app->headers()));
     $app->reset();
     $app->render('view', array('controller' => 'foo'));
     $this->assertEquals('foo', $app->output());
     $this->assertTrue(in_array('Content-Type: text/html;charset=utf-8', $app->headers()));
     $app->reset();
     $app->param('format', 'html');
     $app->render('view', array('controller' => 'foo'));
     $this->assertEquals('foo', $app->output());
     $this->assertTrue(in_array('Content-Type: text/html;charset=utf-8', $app->headers()));
     $app->reset();
     $app->layout('layout');
     $app->render('view', array('controller' => 'foo'));
     $this->assertStringStartsWith('<!DOCTYPE html>', $app->output());
     $this->assertRegExp('/foo<\\/body>/', $app->output());
     $this->assertTrue(in_array('Content-Type: text/html;charset=utf-8', $app->headers()));
     $app->reset();
     $app->render('view', array('controller' => 'foo'), 'json');
     $this->assertEquals(json_encode(array('status' => 'success', 'data' => array('controller' => 'foo'))), $app->output());
     $this->assertTrue(in_array('Content-Type: application/json;charset=utf-8', $app->headers()));
     $app->reset();
     $app->view(array('view', 'json'), function () {
         return 'bar';
     });
     $app->render('view', array('controller' => 'foo'), 'json');
     $this->assertEquals('bar', $app->output());
 }
Example #27
0
 /**
  * Сброс пароля
  */
 public function reset()
 {
     if (User::check()) {
         App::abort(403);
     }
     $key = Request::input('key');
     $errors = [];
     if (!$key) {
         $errors['key'] = 'Отсутствует ключ для сброса пароля';
     }
     if (!$errors && !($user = User::find_by_reset_code($key))) {
         $errors['email'] = 'Пользователь с данным ключем не найден';
     }
     if (!$errors) {
         if (Request::isMethod('post')) {
             $new_password = Request::input('password');
             $user->new_password = $new_password;
             $user->updated_at = new Datetime();
             if ($user->save()) {
                 $user->update_attribute('reset_code', null);
                 App::setFlash('success', 'Новый пароль успешно сохранен!');
                 App::redirect('/');
             } else {
                 App::setFlash('danger', $errors);
                 App::setInput($_POST);
             }
             App::redirect('/reset');
         }
         App::view('users.reset');
     } else {
         App::setFlash('danger', $errors);
         App::redirect('/');
     }
 }
Example #28
0
use Config\System as Config;
$form = new Mobicms\Form\Form(['action' => App::request()->getUri()]);
if (Config::$usrRegAllow) {
    $form->title('TMP')->element('text', 'nickname', ['label' => _g('Choose Nickname'), 'description' => _g('Min. 2, Max. 20 Characters.<br>Allowed letters are Cyrillic and Latin alphabet, numbers, spaces and punctuation - = @ ! ? ~ . _ ( ) [ ] *'), 'required' => true]);
    if (Config::$usrRegEmail) {
        $form->element('text', 'email', ['label' => _g('Your Email'), 'description' => _g('Please correctly specify your email address. This address will be sent a confirmation code to your registration.'), 'required' => true]);
    }
    $form->element('password', 'newpass', ['label' => _g('Password'), 'required' => true])->element('password', 'newconf', ['label' => _g('Repeat password'), 'description' => _g('The password length min. 3 characters'), 'required' => true])->element('radio', 'sex', ['label' => _g('Gender'), 'checked' => 'm', 'items' => ['m' => '<i class="male lg fw"></i>' . _g('Male'), 'w' => '<i class="female lg fw"></i>' . _g('Female')]])->divider(8)->captcha()->element('text', 'captcha', ['label_inline' => _g('Verification code'), 'class' => 'small', 'maxlenght' => 5, 'reset_value' => ''])->divider()->element('submit', 'submit', ['value' => _g('Sign Up'), 'class' => 'btn btn-primary'])->html('<a class="btn btn-link" href="' . App::request()->getBaseUrl() . '/login/">' . _g('Cancel') . '</a>')->validate('captcha', 'captcha');
    if (Config::$usrRegEmail) {
        $form->validate('email', 'lenght', ['min' => 5, 'max' => 50])->validate('email', 'email');
    }
    $form->validate('nickname', 'lenght', ['min' => 2, 'max' => 20])->validate('nickname', 'nickname')->validate('newpass', 'lenght', ['continue' => false, 'min' => 3])->validate('newconf', 'compare', ['compare_field' => 'newpass', 'error' => _g("Passwords don't coincide")])->validate('nickname', 'nickoccupied', ['valid' => true]);
    if ($form->process() === true) {
        $token = Includes\Functions::generateToken();
        $stmt = App::db()->prepare("\n          INSERT INTO `user__` SET\n          `nickname`      = ?,\n          `password`      = ?,\n          `token`         = ?,\n          `email`         = ?,\n          `rights`        = 0,\n          `level`         = ?,\n          `sex`           = ?,\n          `join_date`     = ?,\n          `last_visit`    = ?,\n          `about`         = ?,\n          `reputation`  = ?\n        ");
        $stmt->execute([$form->output['nickname'], password_hash($form->output['newpass'], PASSWORD_DEFAULT), $token, Config::$usrRegEmail ? $form->output['email'] : '', Config::$usrRegAllow && !Config::$usrRegModeration && !Config::$usrRegEmail ? 1 : 0, $form->output['sex'], time(), time(), '', '']);
        //TODO: Добавить подтверждение по Email
        //TODO: Добавить отправку Welcome Message
        //TODO: Добавить страницу с приветствием
        // Запускаем пользователя на сайт
        $userid = App::db()->lastInsertId();
        setcookie('user_id', $userid, time() + 3600 * 24 * 31, '/');
        setcookie('token', $token, time() + 3600 * 24 * 31, '/');
        $_SESSION['user_id'] = $userid;
        $_SESSION['token'] = $token;
        App::redirect(App::request()->getBaseUrl());
    }
}
App::view()->form = $form->display();
App::view()->setTemplate('registration.php');
Example #29
0
/*
 * mobiCMS Content Management System (http://mobicms.net)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://mobicms.net mobiCMS Project
 * @copyright   Copyright (C) mobiCMS Community
 * @license     LICENSE.md (see attached file)
 */
defined('MOBICMS') or die('Error: restricted access');
use Config\System as Config;
$uri = App::request()->getUri();
$form = new Mobicms\Form\Form(['action' => $uri]);
$form->title(_dg('Clear Cache'))->html('<span class="description">' . _dg('The Cache clearing is required after installing a new language or upgrade existing ones.') . '</span>')->element('submit', 'update', ['value' => _dg('Clear Cache'), 'class' => 'btn btn-primary btn-xs'])->title(_dg('Default Language'))->element('radio', 'lng', ['checked' => Config::$lng, 'description' => _dg('If the choice is prohibited, the language will be forced to set for all visitors. If the choice is allowed, it will be applied only in the case, if requested by the client language is not in the system.'), 'items' => App::lng()->getLocalesList()])->element('checkbox', 'lngSwitch', ['checked' => Config::$lngSwitch, 'label_inline' => _dg('Allow to choose'), 'description' => _dg('Allow visitors specify the desired language from the list of available in the system. Including activated auto select languages by signatures of the browser.')])->divider()->element('submit', 'submit', ['value' => _g('Save'), 'class' => 'btn btn-primary'])->html('<a class="btn btn-link" href="../">' . _g('Back') . '</a>');
if ($form->process() === true) {
    if (isset($form->input['update'])) {
        // Обновляем кэш
        App::lng()->clearCache();
        App::redirect($uri . '?cache');
    } else {
        // Записываем настройки
        App::session()->remove('lng');
        (new Mobicms\Config\WriteHandler())->write('System', $form->output);
        App::redirect($uri . '?saved');
    }
}
App::view()->form = $form->display();
App::view()->setTemplate('edit_form.php');
Example #30
0
 /**
  * Приборная панель
  */
 public function index()
 {
     App::view('admin.index');
 }