Example #1
0
 public function __construct()
 {
     $this->session = \App::session();
     // Get user defined locale
     $this->currentLocale = $this->getCurrentLocale();
     $this->cachePath = CACHE_PATH . 'locale';
 }
Example #2
0
 /**
  * Get the user filters
  *
  * @return array The user filters
  */
 public function getFilters()
 {
     if (App::request()->getHeaders('X-List-Filter')) {
         App::session()->getUser()->setOption('admin.user-filter', App::request()->getHeaders('X-List-Filter'));
     }
     return json_decode(App::session()->getUser()->getOptions('admin.user-filter'), true);
 }
Example #3
0
 public static function baseCondition()
 {
     $bid = \App::session('bid', 'adm');
     if (!$bid) {
         return '';
     }
     return "bid={$bid}";
 }
Example #4
0
 protected function captcha(array $option)
 {
     $session = \App::session();
     if (isset($option['value']) && $session->has('captcha') && strtoupper($session->get('captcha')) == strtoupper($option['value'])) {
         return true;
     }
     $this->error[] = _s('The security code is not correct');
     return false;
 }
Example #5
0
function verifyCaptcha($value)
{
    $sess_verify = \App::session('verify');
    $sess_verify_time = \App::session('verify_time');
    if (empty($sess_verify) || empty($sess_verify_time)) {
        return [0, '已失效'];
    }
    if (time() > $sess_verify_time + 60) {
        return [0, '已过期'];
    }
    if (md5(strtolower($value)) != $sess_verify) {
        return [0, '错误'];
    }
    return true;
}
Example #6
0
 public function __construct(array $option)
 {
     $this->session = \App::session();
     $this->form = $option;
     if (!isset($this->form['name'])) {
         $this->form['name'] = 'form';
     }
     if (isset($option['method']) && $option['method'] == 'get') {
         $this->form['method'] = 'get';
         $this->input = filter_input_array(INPUT_GET);
     } else {
         $this->form['method'] = 'post';
         $this->input = filter_input_array(INPUT_POST);
     }
     $this->successMessage = _s('Data saved successfully');
     $this->errorMessage = _s('Errors occurred');
 }
Example #7
0
 /**
  * Create or edit an user
  */
 public function edit()
 {
     $roles = array_map(function ($role) {
         return $role->getLabel();
     }, Role::getAll('id'));
     $user = User::getByUsername($this->username);
     $param = array('id' => 'user-form', 'upload' => true, 'model' => 'User', 'reference' => array('username' => $this->username), 'fieldsets' => array('general' => array('nofieldset' => true, new TextInput(array('name' => 'username', 'required' => true, 'unique' => true, 'readonly' => $user && $user->id !== App::session()->getUser()->id, 'insert' => !$user || $user->id === App::session()->getUser()->id, 'label' => Lang::get($this->_plugin . '.user-form-username-label'))), new EmailInput(array('name' => 'email', 'required' => true, 'unique' => true, 'readonly' => $user && $user->id !== App::session()->getUser()->id, 'insert' => !$user || $user->id !== App::session()->getUser()->id, 'label' => Lang::get($this->_plugin . '.user-form-email-label'))), new CheckboxInput(array('name' => 'active', 'label' => Lang::get($this->_plugin . '.user-form-active-label'))), new SelectInput(array('name' => 'roleId', 'options' => $roles, 'label' => Lang::get($this->_plugin . '.user-form-roleId-label'))), $user ? null : new PasswordInput(array('name' => 'password', 'required' => true, 'label' => Lang::get($this->_plugin . '.user-form-password-label'), 'encrypt' => array('Hawk\\Crypto', 'saltHash'))), $user ? null : new PasswordInput(array('name' => 'passagain', 'label' => Lang::get($this->_plugin . '.user-form-passagain-label'), 'required' => true, 'compare' => 'password', 'independant' => true)), new HiddenInput(array('name' => 'createTime', 'default' => time()))), '_submits' => array(new SubmitInput(array('name' => 'valid', 'value' => Lang::get('main.valid-button'))), new DeleteInput(array('name' => 'delete', 'value' => Lang::get('main.delete-button'), 'notDisplayed' => !($user && $user->isRemovable()))), new ButtonInput(array('name' => 'cancel', 'value' => Lang::get('main.cancel-button'), 'onclick' => 'app.dialog("close")')))), 'onsuccess' => 'app.dialog("close"); app.lists["admin-users-list"].refresh();');
     $form = new Form($param);
     if (!$form->submitted()) {
         return View::make(Theme::getSelected()->getView("dialogbox.tpl"), array('page' => $form, 'title' => Lang::get($this->_plugin . '.user-form-title'), 'icon' => 'user'));
     } else {
         if ($form->submitted() == "delete") {
             $this->remove();
         } else {
             if ($form->check()) {
                 return $form->register();
             }
         }
     }
 }
Example #8
0
 /**
  * 登录页面
  *
  * @return \Core\Http\Response
  */
 public function loginAction()
 {
     if ($this->adminId > 0) {
         return $this->goHome();
     }
     $session = \App::session();
     if ($this->request->isMethod('post')) {
         $userName = $this->getPost('username');
         $password = $this->getPost('password');
         $remember = $this->getPost('remember', 0);
         $adminInfo = AdminModel::getInstance()->getAdminByName($userName);
         if ($adminInfo && $adminInfo['password'] == md5($password . $adminInfo['salt'])) {
             $this->setLoginAuth($adminInfo['id'], $adminInfo['password'], $remember);
             AdminModel::getInstance()->updateAdmin($adminInfo['id'], array('last_login' => NOW, 'last_ip' => $this->request->getClientIp()));
             return $this->redirect(URL('main/index'));
         }
         $session->setFlash('error', '帐号或密码错误');
     }
     $this->assign(['error' => $session->getFlash('error')]);
     return $this->display();
 }
Example #9
0
 /**
  * Get the items available for a specific user
  *
  * @param User $user The user. If not set, the current session user is set
  *
  * @return array The list of items
  */
 public static function getAvailableItems($user = null)
 {
     if ($user == null) {
         $user = App::session()->getUser();
     }
     // Get all items
     $items = self::getListByExample(new DBExample(array('active' => 1)), self::$primaryColumn, array(), array('parentId' => 'ASC', 'order' => 'ASC'));
     // Filter unavailable items (that are not active or not accessible)
     $items = array_filter($items, function ($item) use($user) {
         return $item->isVisible($user);
     });
     // Put the sub items under their parent item
     foreach ($items as $item) {
         if ($item->parentId) {
             $items[$item->parentId]->visibleItems[$item->order] = $item;
             unset($items[$item->id]);
         }
     }
     $items = array_values($items);
     foreach ($items as $item) {
         $item->visibleItems = array_values($item->visibleItems);
     }
     return $items;
 }
Example #10
0
 /**
  * @covers \Phix\App::session
  */
 public function testSession()
 {
     $app = new App();
     $this->assertNull($app->session('foo'));
     $app->session('foo', 'bar');
     $this->assertSame('bar', $app->session('foo'));
     $app->session('foo', null);
     $this->assertArrayNotHasKey('foo', $_SESSION);
     $ret = $app->session('foo', function () {
         return array('bar', 'baz');
     });
     $this->assertSame(array('bar', 'baz'), $app->session('foo'));
     $this->assertEquals($ret, $app);
 }
Example #11
0
 /**
  * Display and treat the form to reset the user's password
  */
 public function resetPassword()
 {
     $form = new Form(array('id' => 'reset-password-form', 'fieldsets' => array('form' => array(new TextInput(array('name' => 'code', 'required' => true, 'label' => Lang::get($this->_plugin . '.reset-pwd-form-code-label'))), new PasswordInput(array('name' => 'password', 'required' => true, 'label' => Lang::get($this->_plugin . '.reset-pwd-form-password-label'), 'encrypt' => array('\\Hawk\\Crypto', 'saltHash'))), new PasswordInput(array('name' => 'confirmation', 'required' => true, 'compare' => 'password', 'label' => Lang::get($this->_plugin . '.reset-pwd-form-confirmation-label')))), 'submits' => array(new SubmitInput(array('name' => 'valid', 'label' => Lang::get($this->_plugin . '.valid-button'))), new ButtonInput(array('name' => 'cancel', 'label' => Lang::get($this->_plugin . '.cancel-button'), 'href' => App::router()->getUri('login'), 'target' => 'dialog')))), 'onsuccess' => 'app.dialog(app.getUri("login"));'));
     if (!$form->submitted()) {
         return Dialogbox::make(array('title' => Lang::get($this->_plugin . '.reset-pwd-form-title'), 'icon' => 'lock-alt', 'page' => $form));
     } else {
         if ($form->check()) {
             // Check the verficiation code
             if ($form->getData('code') !== Crypto::aes256Decode(App::session()->getData('forgottenPassword.code'))) {
                 $form->error('code', Lang::get($this->_plugin . '.reset-pwd-form-bad-verification-code'));
                 return $form->response(Form::STATUS_CHECK_ERROR);
             }
             try {
                 $user = User::getByEmail(App::session()->getData('forgottenPassword.email'));
                 if ($user) {
                     $user->set('password', $form->inputs['password']->dbvalue());
                     $user->save();
                 } else {
                     return $form->response(Form::STATUS_ERROR, App::session()->getData('forgottenPassword.email'));
                 }
                 return $form->response(Form::STATUS_SUCCESS, Lang::get($this->_plugin . '.reset-pwd-form-success'));
             } catch (\Exception $e) {
                 return $form->response(Form::STATUS_ERROR, Lang::get($this->_plugin . '.reset-pwd-form-error'));
             }
         }
     }
 }
Example #12
0
 /**
  * Compute the routing, and execute the controller method associated to the URI
  */
 public function route()
 {
     $path = str_replace(BASE_PATH, '', parse_url(App::request()->getUri(), PHP_URL_PATH));
     // Scan each row
     foreach ($this->routes as $route) {
         if ($route->match($path)) {
             // The URI matches with the route
             $this->currentRoute =& $route;
             // Check if the route is accessible with the current method
             if (!$route->isCallableBy(App::request()->getMethod())) {
                 throw new BadMethodException($route->url, App::request()->getMethod());
             }
             // Emit an event, saying the routing action is finished
             $event = new Event('after-routing', array('route' => $route));
             $event->trigger();
             $route = $event->getData('route');
             if (!$route->isAccessible()) {
                 // The route is not accessible
                 App::logger()->warning(sprintf('A user with the IP address %s tried to access %s without the necessary privileges', App::request()->clientIp(), App::request()->getUri()));
                 if (!App::session()->isLogged()) {
                     throw new UnauthorizedException();
                 } else {
                     throw new ForbiddenException();
                 }
             }
             // The route authentications are validated
             list($classname, $method) = explode(".", $route->action);
             // call a controller method
             $this->currentController = $classname::getInstance($route->getData());
             App::logger()->debug(sprintf('URI %s has been routed => %s::%s', App::request()->getUri(), $classname, $method));
             // Set the controller result to the HTTP response
             App::response()->setBody($this->currentController->{$method}());
             return;
         }
     }
     App::logger()->warning('The URI ' . App::request()->getUri() . ' has not been routed');
     throw new PageNotFoundException();
 }
Example #13
0
     App::router()->get('delete-plugin', 'plugins/{plugin}/remove', array('where' => array('plugin' => Plugin::NAME_PATTERN), 'action' => 'PluginController.delete'));
     // Create a new plugin structure
     App::router()->any('create-plugin', 'plugins/_new', array('action' => 'PluginController.create'));
     // Update a plugin
     App::router()->get('update-plugin', 'plugins/{plugin}/update', array('where' => array('plugin' => Plugin::NAME_PATTERN), 'action' => 'PluginController.update'));
     // Display number of updates in menu
     if (App::session()->isAllowed('admin.all')) {
         Event::on(\Hawk\Plugins\Main\MainController::EVENT_AFTER_GET_MENUS, function (Event $event) {
             SearchUpdatesWidget::getInstance()->display();
         });
     }
 });
 /**
  * Manage the languages and languages keys
  */
 App::router()->auth(App::session()->isAllowed('admin.languages'), function () {
     // list all the supported languages
     App::router()->any('manage-languages', 'languages/', array('action' => 'LanguageController.index'));
     App::router()->get('language-keys-list', 'languages/keys', array('action' => 'LanguageController.listKeys'));
     // Save the translations
     App::router()->post('save-language-keys', 'languages/keys/save', array('action' => 'LanguageController.editKeys'));
     // Edit a language
     App::router()->any('edit-language', 'languages/{tag}', array('where' => array('tag' => '[a-z]{2}|new'), 'action' => 'LanguageController.editLanguage'));
     // Delete a language
     App::router()->get('delete-language', 'languages/{tag}/delete', array('where' => array('tag' => '[a-z]{2}'), 'action' => 'LanguageController.deleteLanguage'));
     // Add a language key
     App::router()->post('add-language-key', 'languages/keys/add', array('action' => 'LanguageController.addKey'));
     // Delete a translation
     App::router()->any('delete-translation', 'languages/keys/{plugin}/{key}/{tag}/clean', array('where' => array('plugin' => '[\\w\\-]+', 'key' => '[\\w\\-]+', 'tag' => '[a-z]{2}'), 'action' => 'LanguageController.deleteTranslation'));
     // Import language file
     App::router()->any('import-language-keys', 'languages/import', array('action' => 'LanguageController.import'));
Example #14
0
 /**
  * Constructor
  *
  * @param arary $params The parameter of the list
  */
 public function __construct($params)
 {
     // Default values
     $this->emptyMessage = Lang::get('main.list-no-result');
     $this->action = getenv('REQUEST_URI');
     $this->refresh = !!App::request()->getParams('refresh');
     // Get the values from the parameters array
     $this->map($params);
     if ($this->data === null) {
         if (!class_exists($this->model)) {
             $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
             $reflection = new \ReflectionClass($trace[1]['class']);
             $this->model = $reflection->getNamespaceName() . '\\' . $this->model;
         }
         if ($this->model == self::DEFAULT_MODEL) {
             if (!isset($this->table)) {
                 throw new \Exception('ItemList contructor expects property "table" or "model" to be set');
             }
             if (!isset($this->reference)) {
                 $this->reference = 'id';
             }
         } else {
             $model = $this->model;
             if (!isset($this->reference)) {
                 $this->reference = $model::getPrimaryColumn();
             }
             if (!isset($this->table)) {
                 $this->table = $model::getTable();
             }
             $this->dbname = $model::getDbName();
         }
         $this->refAlias = is_array($this->reference) ? reset($this->reference) : $this->reference;
         $this->refField = is_array($this->reference) ? reset(array_keys($this->reference)) : $this->reference;
         $this->dbo = DB::get($this->dbname);
     }
     // initialize controls
     foreach ($this->controls as &$button) {
         if (!empty($button['template'])) {
             switch ($button['template']) {
                 case 'refresh':
                     $button = array('icon' => 'refresh', 'type' => 'button', 'onclick' => 'app.lists["' . $this->id . '"].refresh();');
                     break;
                 case 'print':
                     $button = array('icon' => 'print', 'type' => 'button', 'onclick' => 'app.lists["' . $this->id . '"].print();');
                     break;
             }
         }
     }
     // Get the filters sent by POST or registered in COOKIES
     $parameters = array('searches', 'sorts', 'lines', 'page');
     if (!$this->navigation) {
         $this->lines = self::ALL_LINES;
     }
     if (App::request()->getHeaders('X-List-Filter-' . $this->id)) {
         App::session()->getUser()->setOption('main.list-' . $this->id, App::request()->getHeaders('X-List-Filter-' . $this->id));
     }
     $this->userParam = json_decode(App::session()->getUser()->getOptions('main.list-' . $this->id), true);
     foreach ($parameters as $name) {
         if (!empty($this->userParam[$name])) {
             $this->{$name} = $this->userParam[$name];
         }
     }
     // initialize fields default values
     foreach ($this->fields as $name => &$field) {
         if (is_array($field)) {
             $field = new ItemListField($name, $field, $this);
             if (isset($this->searches[$name])) {
                 $field->searchValue = $this->searches[$name];
             }
             if (!empty($this->sorts[$name])) {
                 $field->sortValue = $this->sorts[$name];
             }
         } else {
             unset($this->fields[$name]);
         }
     }
     $event = new Event('list.' . $this->id . '.instanciated', array('list' => $this));
     $event->trigger();
 }
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');
//TODO: может удалить?
if (App::session()->has('ref')) {
    App::session()->remove('ref');
}
App::view()->total_users = App::db()->query('SELECT COUNT(*) FROM `user__`')->fetchColumn();
App::view()->setTemplate('index.php');
Example #16
0
     $app->session('basketTotalItems', $basketTotalItems);
     $app->session('basketTotalPrice', $basketTotalPrice);
     if ($ajax) {
         return json_encode(array('ok' => true, 'productId' => $product->id, 'productName' => $product->name, 'productNewCount' => isset($basket[$product->id]) ? $basket[$product->id] : 0, 'basketTotalItems' => $basketTotalItems, 'basketTotalPrice' => $basketTotalPrice, 'basketTotalPriceFormatted' => Product::formatPrice($basketTotalPrice), 'aprtData' => array('pageType' => $count > 0 ? \Actionpay\APRT::PAGETYPE_CART_ADD : \Actionpay\APRT::PAGETYPE_CART_REMOVE, 'currentProduct' => array('id' => $product->id, 'name' => $product->name, 'price' => $product->price))));
     } else {
         $app->redirect($_SERVER['HTTP_REFERER'] ?: '/');
         return '';
     }
 });
 /**
  * http://demoshop.actionpay.ru/basket
  * Страница корзины
  */
 $app->page('/basket', function () use($app) {
     $basket = $app->session('basket');
     if (!empty($basket)) {
         $products = Product::getAll(array('id' => array_keys($basket)), array('name' => true));
     } else {
         $products = array();
     }
     $aprtData = array('pageType' => \Actionpay\APRT::PAGETYPE_BASKET, 'basketProducts' => array());
     foreach ($products as $product) {
         $aprtData['basketProducts'][] = array('id' => $product->id, 'name' => $product->name, 'price' => $product->price, 'quantity' => $basket[$product->id]);
     }
     return $app->render('page_basket', array('title' => 'Корзина', 'products' => $products, 'basket' => $basket, 'basketTotalItems' => $app->session('basketTotalItems') ?: 0, 'basketTotalPrice' => $app->session('basketTotalPrice') ?: 0, 'aprtData' => $aprtData));
 });
 /**
  * http://demoshop.actionpay.ru/order
  * Страница оформления заказа
  */
 $app->page('/order', function ($name = null, $address = null, $phone = null) use($app) {
     $basket = $app->session('basket');
Example #17
0
 /**
  * Create or edit an user
  */
 public function edit()
 {
     $user = App::session()->getUser();
     $roles = array_map(function ($role) {
         return $role->getLabel();
     }, Role::getAll('id'));
     $param = array('id' => 'user-profile-form', 'upload' => true, 'object' => $user, 'fieldsets' => array('general' => array('legend' => Lang::get('admin.user-form-general-legend'), new TextInput(array('name' => 'username', 'required' => true, 'label' => Lang::get('admin.user-form-username-label'), 'disabled' => true)), new EmailInput(array('name' => 'email', 'required' => true, 'label' => Lang::get('admin.user-form-email-label')))), 'profile' => array('legend' => Lang::get('admin.user-form-profile-legend')), '_submits' => array(new SubmitInput(array('name' => 'valid', 'value' => Lang::get($this->_plugin . '.valid-button'))))), 'onsuccess' => 'app.dialog("close")');
     // Get the user profile questions
     $questions = ProfileQuestion::getAll('name', array(), array('order' => DB::SORT_ASC));
     // Generate the question fields
     foreach ($questions as $question) {
         if ($question->displayInProfile && $question->isAllowedForRole($user->roleId)) {
             $classname = '\\Hawk\\' . ucwords($question->type) . 'Input';
             $field = json_decode($question->parameters, true);
             $field['name'] = $question->name;
             $field['id'] = 'user-form-' . $question->name . '-input';
             $field['independant'] = true;
             $field['label'] = Lang::get('admin.profile-question-' . $question->name . '-label');
             if (isset($field['readonly'])) {
                 if ($field['readonly']) {
                     $field['required'] = false;
                 }
             }
             if ($user) {
                 if ($question->type == "file") {
                     $field['after'] = sprintf('<img src="%s" class="profile-image" />', $user->getProfileData($question->name) ? $user->getProfileData($question->name) : '');
                 } else {
                     $field['default'] = $user->getProfileData($question->name);
                 }
             }
             if ($question->name == 'language') {
                 // Get language options
                 $languages = Language::getAllActive();
                 $options = array();
                 foreach ($languages as $language) {
                     $options[$language->tag] = $language->label;
                 }
                 $field['options'] = $options;
                 if (!$field['default']) {
                     $field['default'] = Option::get($this->_plugin . '.language');
                 }
             }
             $param['fieldsets']['profile'][] = new $classname($field);
         }
     }
     $form = new Form($param);
     if (!$form->submitted()) {
         return NoSidebarTab::make(array('title' => Lang::get('admin.user-form-title'), 'page' => array('content' => $form)));
     } else {
         try {
             foreach ($questions as $question) {
                 if ($question->displayInProfile && $question->isAllowedForRole($user->roleId)) {
                     if ($question->type === 'file') {
                         $upload = Upload::getInstance($question->name);
                         if ($upload) {
                             $file = $upload->getFile(0);
                             $dir = Plugin::current()->getPublicUserfilesDir() . 'img/';
                             $url = Plugin::current()->getUserfilesUrl() . 'img/';
                             if (!is_dir($dir)) {
                                 mkdir($dir, 0755, true);
                             }
                             $basename = uniqid() . $file->extension;
                             $upload->move($file, $dir, $basename);
                             $user->setProfileData($question->name, $url . $basename);
                         }
                     } else {
                         $user->setProfileData($question->name, $form->inputs[$question->name]->dbvalue());
                     }
                 }
             }
             $user->saveProfile();
             if ($form->getData('email') !== $user->email) {
                 // The user asked to reset it email
                 // Check this email is not used by another user on the application
                 $existingUser = User::getByExample(new DBExample(array('id' => array('$ne' => $user->id), 'email' => $form->getData('email'))));
                 if ($existingUser) {
                     return $form->response(Form::STATUS_CHECK_ERROR, Lang::get($this->_plugin . '.reset-email-already-used'));
                 }
                 // Send the email to validate the new email
                 // Create the token to validate the new email
                 $tokenData = array('userId' => $user->id, 'currentEmail' => $user->email, 'newEmail' => $form->getData('email'), 'createTime' => time());
                 $token = base64_encode(Crypto::aes256Encode(json_encode($tokenData)));
                 // Create the email content
                 $emailContent = View::make($this->getPlugin()->getView('change-email-validation.tpl'), array('sitename' => Option::get($this->_plugin . '.sitename'), 'validationUrl' => App::router()->getUrl('validate-new-email', array('token' => $token))));
                 $email = new Mail();
                 $email->to($form->getData('email'))->from(Option::get('main.mailer-from'), Option::get('main.mailer-from-name'))->title(Lang::get($this->_plugin . '.reset-email-title', array('sitename' => Option::get($this->_plugin . '.sitename'))))->content($emailContent)->subject(Lang::get($this->_plugin . '.reset-email-title', array('sitename' => Option::get($this->_plugin . '.sitename'))))->send();
                 return $form->response(Form::STATUS_SUCCESS, Lang::get($this->_plugin . '.user-profile-update-success-with-email'));
             }
             return $form->response(Form::STATUS_SUCCESS, Lang::get($this->_plugin . '.user-profile-update-success'));
         } catch (Exception $e) {
             return $form->response(Form::STATUS_ERROR, Lang::get($this->_plugin . '.user-profile-update-error'));
         }
     }
 }
Example #18
0
 /**
  * Check of the user is removable. A user is removable if he's not the one executing the current script,
  * and if he's not a guest or the main application administrator
  *
  * @return bool
  */
 public function isRemovable()
 {
     return $this->id != App::session()->getUser()->id && $this->id != self::ROOT_USER_ID && $this->id != self::GUEST_USER_ID;
 }
Example #19
0
    /*** Access to the OS database (MySQL) ***/
    try {
        DB::add(MAINDB, App::conf()->get('db.maindb'));
        App::getInstance()->singleton('db', DB::get(MAINDB));
    } catch (DBException $e) {
        // The database is not configured, redirect to the installation
        exit(DEBUG_MODE ? $e->getMessage() : Lang::get('main.connection-error'));
    }
}
/*** Open the session ***/
if (App::conf()->has('db')) {
    session_set_save_handler(new DatabaseSessionHandler());
}
session_set_cookie_params((int) App::conf()->get('session.lifetime'), '/');
session_start();
App::session()->init();
/*** Constants depending to the options ***/
if (App::request()->getCookies('language')) {
    define('LANGUAGE', App::request()->getCookies('language'));
} elseif (App::conf()->has('db')) {
    if (App::session()->getUser()->getProfileData('language')) {
        define('LANGUAGE', App::session()->getUser()->getProfileData('language'));
    } elseif (Option::get('main.language')) {
        define('LANGUAGE', Option::get('main.language'));
    }
} else {
    define('LANGUAGE', Lang::DEFAULT_LANGUAGE);
}
/*** Timezone ***/
define("TIMEZONE", App::conf()->has('db') && Option::get('main.timezone') ? Option::get('main.timezone') : DEFAULT_TIMEZONE);
date_default_timezone_set(TIMEZONE);
Example #20
0
 * Pages available for logged in users
 */
App::router()->auth(App::session()->isLogged(), function () {
    // Edit the logged user's profile
    App::router()->any('edit-profile', '/profile/edit/{userId}', array('where' => array('userId' => '\\d+'), 'default' => array('userId' => App::session()->getUser()->id), 'action' => 'UserProfileController.edit', 'auth' => function ($route) {
        return !$route->getData('userId') || $route->getData('userId') == App::session()->getUser()->id;
    }));
    // Change the password
    App::router()->any('change-password', '/profile/change-password', array('action' => 'UserProfileController.changePassword'));
    // Logout
    App::router()->get('logout', '/logout', array('action' => 'LoginController.logout'));
});
/**
 * The pages available only if not logged
 */
App::router()->auth(!App::session()->isLogged(), function () {
    //Login
    App::router()->any('login', '/login', array('action' => 'LoginController.login'));
    // Register
    App::router()->auth(Option::get('main.open-register'), function () {
        App::router()->any('register', '/register', array('action' => 'LoginController.register'));
        App::router()->get('validate-registration', '/register/{token}', array('where' => array('token' => '[^\\s]+'), 'action' => 'LoginController.validateRegister'));
    });
    // Ask for a new password
    App::router()->any('forgotten-password', '/forgotten-password', array('action' => 'LoginController.forgottenPassword'));
    // Reset the forgotten password
    App::router()->any('reset-password', '/reset-password', array('action' => 'LoginController.resetPassword'));
});
// Validate of the new email address, that has been modified in the profile edition page
App::router()->get('validate-new-email', '/profile/change-email/{token}', array('where' => array('token' => '[\\w\\=]+'), 'action' => 'UserProfileController.validateNewEmail'));
// The terms of service
Example #21
0
 /**
  * Generate the conf.js file
  */
 public function jsConf()
 {
     $canAccessApplication = App::session()->getUser()->canAccessApplication();
     // Get all routes
     $routes = array();
     foreach (App::router()->getRoutes() as $name => $route) {
         if ($route->isAccessible()) {
             $routes[$name] = array('url' => $route->url, 'where' => $route->where, 'default' => $route->default, 'pattern' => $route->pattern, 'duplicable' => !empty($route->duplicable));
         }
     }
     // Get all Lang labels
     $keys = array('main' => Lang::keys('javascript'), 'form' => Lang::keys('form'));
     $keys = json_encode($keys, JSON_HEX_APOS | JSON_HEX_QUOT);
     // Get the pages to open
     $pages = array();
     if (App::session()->isLogged() && Option::get($this->_plugin . '.open-last-tabs') && App::request()->getCookies('open-tabs')) {
         // Open the last tabs the users opened before logout
         $pages = json_decode(App::request()->getCookies('open-tabs'), true);
         $pages = array_values(array_filter($pages));
     }
     if (empty($pages)) {
         $pages[] = App::router()->getUri('new-tab');
     }
     // Get the theme variables
     $theme = Theme::getSelected();
     $editableVariables = $theme->getEditableVariables();
     $initVariables = array();
     foreach ($editableVariables as $variable) {
         $initVariables[$variable['name']] = $variable['default'];
     }
     // Get the url for the new tab
     $newTabUrl = App::router()->getUri('new-tab');
     if (Option::get('main.home-page-type') == 'page') {
         $newTabUrl = App::router()->getUri(Option::get('main.home-page-item'));
     }
     $mainMenu = $this->getMainMenu();
     App::response()->setContentType('javascript');
     return View::make(Plugin::current()->getView('conf.js.tpl'), array('keys' => $keys, 'routes' => json_encode($routes, JSON_HEX_APOS | JSON_HEX_QUOT | JSON_PRETTY_PRINT), 'lastTabs' => json_encode($pages, JSON_HEX_APOS | JSON_HEX_QUOT | JSON_PRETTY_PRINT), 'accessible' => $canAccessApplication, 'less' => array('initVars' => json_encode($initVariables, JSON_HEX_APOS | JSON_HEX_QUOT | JSON_PRETTY_PRINT)), 'newTabUrl' => $newTabUrl, 'mainMenu' => json_encode($mainMenu, JSON_HEX_APOS | JSON_HEX_QUOT | JSON_PRETTY_PRINT)));
 }
Example #22
0
 private function editAdmin()
 {
     $adminModel = AdminModel::getInstance();
     $session = \App::session();
     $id = intval($this->get('id'));
     if ($this->request->isMethod('post')) {
         $password1 = trim($this->get('password1'));
         $password2 = trim($this->get('password2'));
         $power = (array) $this->get('power', []);
         $data = ['real_name' => $this->get('real_name', ''), 'email' => $this->get('email', ''), 'power' => implode(',', $power), 'sex' => intval($this->get('sex', 1))];
         if (!empty($password1)) {
             if (strlen($password1) < 6) {
                 $session->setFlash('error_password1', '密码长度必须大于6位');
                 $session->setFlash('password1', $password1);
                 return $this->goBack();
             }
             if ($password1 != $password2) {
                 $session->setFlash('error_password2', '两次输入的密码不一致');
                 $session->setFlash('password1', $password1);
                 return $this->goBack();
             }
             $data['salt'] = Strings::random(10);
             $data['password'] = md5($password1 . $data['salt']);
         }
         $adminModel->updateAdmin($id, $data);
         return $this->redirect(URL(CUR_ROUTE));
     }
     $adminInfo = $adminModel->getAdmin($id);
     $this->assign(['adminInfo' => $adminInfo, 'powerList' => $this->getPowerList($adminInfo['power']), 'password1' => $session->getFlash('password1'), 'error_password1' => $session->getFlash('error_password1'), 'error_password2' => $session->getFlash('error_password2')]);
     $this->display('system/editadmin');
 }
Example #23
0
<div class="content form-container">
    <div style="text-align: center">
        <form action="<?php 
echo App::request()->getUri();
?>
" method="post">
            <fieldset>
                <legend><?php 
echo _g('Symbols on the picture');
?>
</legend>
                <br/>
                <?php 
$captcha = new Mobicms\Captcha\Captcha();
$code = $captcha->generateCode();
App::session()->set('captcha', $code);
echo '<img alt="' . _g('If you do not see the picture with the code, turn the graphics support in your browser and refresh the page') . '" width="' . $captcha->width . '" height="' . $captcha->height . '" src="' . $captcha->generateImage($code) . '"/>';
if (isset($this->error)) {
    echo '<span class="error-text">' . $this->error . '<br/></span>';
}
?>
                <br/>
                <input id="captcha" type="text" style="width: 100px; text-align: center" maxlength="5"
                       name="captcha" <?php 
echo isset($this->error['captcha']) ? 'class="error"' : '';
?>
/>
            </fieldset>
            <fieldset>
                <input type="submit" name="submit" class="btn btn-primary" value="<?php 
echo _g('Continue');
Example #24
0
function sys_boot()
{
    // our central App object
    App::init();
    /*
     * Load the configuration file which contains our DB credentials.
     * Ignore errors. If the file doesn't exist or is empty, we are running in
     * installation mode.
     */
    // miniApp is a conversion object from old style .htconfig.php files
    $a = new miniApp();
    App::$install = file_exists('.htconfig.php') && filesize('.htconfig.php') ? false : true;
    @(include '.htconfig.php');
    if (!defined('UNO')) {
        define('UNO', 0);
    }
    if (array_key_exists('default_timezone', get_defined_vars())) {
        App::$config['system']['timezone'] = $default_timezone;
    }
    $a->convert();
    App::$timezone = App::$config['system']['timezone'] ? App::$config['system']['timezone'] : 'UTC';
    date_default_timezone_set(App::$timezone);
    /*
     * Try to open the database;
     */
    require_once 'include/dba/dba_driver.php';
    if (!App::$install) {
        DBA::dba_factory($db_host, $db_port, $db_user, $db_pass, $db_data, $db_type, App::$install);
        if (!DBA::$dba->connected) {
            system_unavailable();
        }
        unset($db_host, $db_port, $db_user, $db_pass, $db_data, $db_type);
        /**
         * Load configs from db. Overwrite configs from .htconfig.php
         */
        load_config('config');
        load_config('system');
        load_config('feature');
        App::$session = new Zotlabs\Web\Session();
        App::$session->init();
        load_hooks();
        call_hooks('init_1');
    }
}
Example #25
0
/*** Define the main paths ***/
define('STATIC_URL', ROOT_URL . '/static/');
define('THEMES_ROOT_URL', STATIC_URL . 'themes/');
define('PLUGINS_ROOT_URL', STATIC_URL . 'plugins/');
/*** Access to the OS database (MySQL) ***/
try {
    DB::add(MAINDB, App::conf()->get('db.maindb'));
    $app->singleton('db', DB::get(MAINDB));
} catch (DBException $e) {
    // The database is not configured, redirect to the installation
    exit(DEBUG_MODE ? $e->getMessage() : Lang::get('main.connection-error'));
}
/*** Open the session ***/
session_set_save_handler(new DatabaseSessionHandler());
session_set_cookie_params((int) App::conf()->get('session.lifetime'), '/');
session_start();
App::session()->init();
/*** Constants depending to the options ***/
define('LANGUAGE', Option::get('main.language'));
/*** Timezone ***/
define("TIMEZONE", Option::get('main.timezone'));
date_default_timezone_set(TIMEZONE);
/*** Initialize the plugins ***/
$plugins = App::conf()->has('db') ? Plugin::getActivePlugins() : array(Plugin::get('main'), Plugin::get('install'));
foreach ($plugins as $plugin) {
    if (is_file($plugin->getStartFile())) {
        include $plugin->getStartFile();
    }
}
$filename = $argv[1];
include $filename;
Example #26
0
 /**
  * Register the submitted data in the database
  *
  * @param bool   $exit    If set to true, the script will output after function execution, not depending on the result
  * @param string $success Defines the message to output if the action has been well executed
  * @param string $error   Defines the message to output if an error occured
  *
  * @return mixed The id of the created or updated element in the database
  */
 public function register($exit = self::EXIT_JSON, $success = "", $error = "")
 {
     try {
         $this->dbaction = self::ACTION_REGISTER;
         if (!isset($this->object) && $this->model == self::DEFAULT_MODEL || !$this->reference) {
             throw new \Exception("The method register of the class Form can be called only if model and reference properties are set");
         }
         if (!$this->object) {
             $model = $this->model;
             $this->object = new $model($this->getData());
         } else {
             $this->object->set($this->reference);
         }
         foreach ($this->inputs as $name => $field) {
             /* Determine if we have to insert this field in the set of inserted values
              * A field can't be inserted if :
              *   it type is in the independant types
              *   the field is defined as independant
              *   the fiels is defined as no insert
              */
             if (!$field->independant && $field->insert !== false && !$field->disabled) {
                 /*** Insert the field value in the set ***/
                 $this->object->set($name, $field->dbvalue());
             }
         }
         if (!$this->new) {
             $this->object->update();
         } else {
             $this->object->save();
         }
         $id = $this->object->getPrimaryColumn();
         $this->addReturn(array('primary' => $this->object->{$id}, 'action' => self::ACTION_REGISTER, 'new' => $this->new));
         $this->status = self::STATUS_SUCCESS;
         App::logger()->info(App::session()->getUser()->username . ' has updated the data on the form ' . $this->id);
         if ($exit) {
             // output the response
             App::response()->setBody($this->response(self::STATUS_SUCCESS, $success ? $success : Lang::get('form.success-register')));
             throw new AppStopException();
         }
         return $this->object->{$id};
     } catch (DBException $e) {
         $this->status = self::STATUS_ERROR;
         App::logger()->error('An error occured while registering data on the form ' . $this->id . ' : ' . $e->getMessage());
         if ($exit) {
             return $this->response(self::STATUS_ERROR, DEBUG_MODE ? $e->getMessage() : ($error ? $error : Lang::get('form.error-register')));
         }
         throw $e;
     }
 }
Example #27
0
 /**
  * Display and treat application settings
  */
 public function settings()
 {
     $languages = array_map(function ($language) {
         return $language->label;
     }, Language::getAll('tag'));
     $roleObjects = Role::getListByExample(new DBExample(array('id' => array('$ne' => 0))), 'id');
     $roles = array();
     foreach ($roleObjects as $role) {
         $roles[$role->id] = Lang::get("roles.role-{$role->id}-label");
     }
     $items = MenuItem::getAvailableItems();
     $menuItems = array();
     foreach ($items as $item) {
         if ($item->action && !preg_match('/^(javascript\\:|#)/', $item->action) && (!$item->target || $item->target == 'newtab')) {
             if ($item->label === 'user.username') {
                 $item->label = App::session()->getUser()->username;
             }
             $menuItems[$item->action] = $item->label;
         } else {
             foreach ($item->visibleItems as $subitem) {
                 if ($item->label === 'user.username') {
                     $item->label = App::session()->getUser()->username;
                 }
                 if (!preg_match('/^(javascript\\:|#)/', $subitem->action) && (!$subitem->target || $subitem->target == 'newtab')) {
                     $menuItems[$subitem->action] = $item->label . " &gt; " . $subitem->label;
                 }
             }
         }
     }
     $api = new HawkApi();
     try {
         $updates = $api->getCoreAvailableUpdates();
     } catch (\Hawk\HawkApiException $e) {
         $updates = array();
     }
     $param = array('id' => 'settings-form', 'upload' => true, 'fieldsets' => array('main' => array(new TextInput(array('name' => 'main_sitename', 'required' => true, 'default' => Option::get('main.sitename'), 'label' => Lang::get('admin.settings-sitename-label'))), new SelectInput(array('name' => 'main_language', 'required' => true, 'options' => $languages, 'default' => Option::get('main.language'), 'label' => Lang::get('admin.settings-language-label'))), new SelectInput(array('name' => 'main_timezone', 'required' => true, 'options' => array_combine(\DateTimeZone::listIdentifiers(), \DateTimeZone::listIdentifiers()), 'default' => Option::get('main.timezone'), 'label' => Lang::get('admin.settings-timezone-label'))), new SelectInput(array('name' => 'main_currency', 'required' => true, 'options' => array('EUR' => 'Euro (€)', 'USD' => 'US Dollar ($)'), 'default' => Option::get('main.currency'), 'label' => Lang::get('admin.settings-currency-label'))), new FileInput(array('name' => 'logo', 'label' => Lang::get('admin.settings-logo-label'), 'after' => Option::get('main.logo') ? '<img src="' . Plugin::get('main')->getUserfilesUrl(Option::get('main.logo')) . '" class="settings-logo-preview" />' : '', 'maxSize' => 200000, 'extensions' => array('gif', 'png', 'jpg', 'jpeg'))), new FileInput(array('name' => 'favicon', 'label' => Lang::get('admin.settings-favicon-label'), 'after' => Option::get('main.favicon') ? '<img src="' . Plugin::get('main')->getUserfilesUrl(Option::get('main.favicon')) . '" class="settings-favicon-preview" />' : '', 'maxSize' => 20000, 'extensions' => array('gif', 'png', 'jpg', 'jpeg', 'ico')))), 'referencing' => call_user_func(function () use($languages) {
         $inputs = array();
         foreach ($languages as $tag => $language) {
             $inputs[] = new TextInput(array('name' => 'main_page-title-' . $tag, 'default' => Option::get('main.page-title-' . $tag)));
             $inputs[] = new TextareaInput(array('name' => 'main_page-description-' . $tag, 'default' => Option::get('main.page-description-' . $tag)));
             $inputs[] = new TextInput(array('name' => 'main_page-keywords-' . $tag, 'default' => Option::get('main.page-keywords-' . $tag)));
         }
         return $inputs;
     }), 'home' => array(new RadioInput(array('name' => 'main_home-page-type', 'options' => array('default' => Lang::get('admin.settings-home-page-type-default'), 'custom' => Lang::get('admin.settings-home-page-type-custom'), 'page' => Lang::get('admin.settings-home-page-type-page')), 'default' => Option::get('main.home-page-type') ? Option::get('main.home-page-type') : 'default', 'label' => Lang::get('admin.settings-home-page-type-label'), 'layout' => 'vertical', 'attributes' => array('e-value' => 'homePage.type'))), new WysiwygInput(array('name' => 'main_home-page-html', 'id' => 'home-page-html', 'label' => Lang::get('admin.settings-home-page-html-label'), 'default' => Option::get('main.home-page-html'))), new SelectInput(array('name' => 'main_home-page-item', 'id' => 'home-page-item', 'label' => Lang::get('admin.settings-home-page-item-label'), 'options' => $menuItems, 'value' => Option::get('main.home-page-item'))), new CheckboxInput(array('name' => 'main_open-last-tabs', 'label' => Lang::get('admin.settings-open-last-tabs'), 'default' => Option::get('main.open-last-tabs'), 'dataType' => 'int'))), 'users' => array(new RadioInput(array('name' => 'main_allow-guest', 'options' => array(0 => Lang::get('main.no-txt'), 1 => Lang::get('main.yes-txt')), 'default' => Option::get('main.allow-guest') ? Option::get('main.allow-guest') : 0, 'label' => Lang::get('admin.settings-allow-guest-label'))), new RadioInput(array('name' => 'main_open-register', 'options' => array(0 => Lang::get('admin.settings-open-register-off'), 1 => Lang::get('admin.settings-open-register-on')), 'layout' => 'vertical', 'label' => Lang::get('admin.settings-open-registers-label'), 'default' => Option::get('main.open-register') ? Option::get('main.open-register') : 0, 'attributes' => array('e-value' => 'register.open'))), new CheckboxInput(array('name' => 'main_confirm-register-email', 'label' => Lang::get('admin.settings-confirm-email-label'), 'default' => Option::get('main.confirm-register-email'), 'dataType' => 'int', 'attributes' => array('e-value' => 'register.checkEmail'))), new WysiwygInput(array('name' => 'main_confirm-email-content', 'id' => 'settings-confirm-email-content-input', 'default' => Option::get('main.confirm-email-content'), 'label' => Lang::get('admin.settings-confirm-email-content-label'), 'labelWidth' => 'auto')), new CheckboxInput(array('name' => 'main_confirm-register-terms', 'label' => Lang::get('admin.settings-confirm-terms-label'), 'default' => Option::get('main.confirm-register-terms'), 'dataType' => 'int', 'labelWidth' => 'auto', 'attributes' => array('e-value' => 'register.checkTerms'))), new WysiwygInput(array('name' => 'main_terms', 'id' => 'settings-terms-input', 'label' => Lang::get('admin.settings-terms-label'), 'labelWidth' => 'auto', 'default' => Option::get('main.terms'))), new SelectInput(array('name' => 'roles_default-role', 'label' => Lang::get('admin.settings-default-role-label'), 'options' => $roles, 'default' => Option::get('roles.default-role')))), 'email' => array(new EmailInput(array('name' => 'main_mailer-from', 'default' => Option::get('main.mailer-from') ? Option::get('main.mailer-from') : App::session()->getUser()->email, 'label' => Lang::get('admin.settings-mailer-from-label'))), new TextInput(array('name' => 'main_mailer-from-name', 'default' => Option::get('main.mailer-from-name') ? Option::get('main.mailer-from-name') : App::session()->getUser()->getDisplayName(), 'label' => Lang::get('admin.settings-mailer-from-name-label'))), new SelectInput(array('name' => 'main_mailer-type', 'default' => Option::get('main.mailer-type'), 'options' => array('mail' => Lang::get('admin.settings-mailer-type-mail-value'), 'smtp' => Lang::get('admin.settings-mailer-type-smtp-value'), 'pop3' => Lang::get('admin.settings-mailer-type-pop3-value')), 'label' => Lang::get('admin.settings-mailer-type-label'), 'attributes' => array('e-value' => 'mail.type'))), new TextInput(array('name' => 'main_mailer-host', 'default' => Option::get('main.mailer-host'), 'label' => Lang::get('admin.settings-mailer-host-label'))), new IntegerInput(array('name' => 'main_mailer-port', 'default' => Option::get('main.mailer-port'), 'label' => Lang::get('admin.settings-mailer-port-label'), 'size' => 4)), new TextInput(array('name' => 'main_mailer-username', 'default' => Option::get('main.mailer-username'), 'label' => Lang::get('admin.settings-mailer-username-label'))), new PasswordInput(array('name' => 'main_mailer-password', 'encrypt' => 'Crypto::aes256Encode', 'decrypt' => 'Crypto::aes256Decode', 'default' => Option::get('main.mailer-password'), 'label' => Lang::get('admin.settings-mailer-password-label'))), new SelectInput(array('name' => 'main_smtp-secured', 'options' => array('' => Lang::get('main.no-txt'), 'ssl' => 'SSL', 'tsl' => 'TSL'), 'label' => Lang::get('admin.settings-smtp-secured-label')))), '_submits' => array(empty($updates) ? new HtmlInput(array('value' => '<span class="btn btn-success">' . Lang::get('admin.hawk-version-up-to-date', array('version' => HAWK_VERSION)) . '</span>')) : new ButtonInput(array('name' => 'update-hawk', 'value' => Lang::get('admin.update-page-update-hawk-btn', array('version' => end($updates)['version'])), 'icon' => 'refresh', 'id' => 'update-hawk-btn', 'attributes' => array('e-click' => 'function(){ updateHawk("' . end($updates)['version'] . '"); }'), 'class' => 'btn-warning')), new SubmitInput(array('name' => 'save', 'value' => Lang::get('main.valid-button'), 'class' => 'pull-right')))));
     $form = new Form($param);
     if (!$form->submitted()) {
         // Display the form
         $this->addCss(Plugin::current()->getCssUrl('settings.less'));
         $page = View::make(Plugin::current()->getView('settings.tpl'), array('form' => $form, 'languages' => $languages));
         $this->addKeysToJavaScript('admin.update-page-confirm-update-hawk');
         $this->addJavaScript(Plugin::current()->getJsUrl('settings.js'));
         return NoSidebarTab::make(array('icon' => 'cogs', 'title' => Lang::get('admin.settings-page-name'), 'description' => Lang::get('admin.settings-page-description'), 'page' => $page));
     } else {
         // treat the form
         try {
             if ($form->check()) {
                 // register scalar values
                 foreach ($form->inputs as $name => $field) {
                     if (!$field instanceof \Hawk\FileInput && !$field instanceof \Hawk\ButtonInput && !$field instanceof \Hawk\HtmlInput) {
                         $value = $field->dbvalue();
                         if ($value === null) {
                             $value = '0';
                         }
                         $optionName = str_replace('_', '.', $name);
                         App::logger()->error("Option name =" . $optionName . 'X');
                         App::logger()->error("basename=" . $value . 'X');
                         Option::set($optionName, $value);
                     } elseif ($field instanceof \Hawk\FileInput) {
                         $upload = Upload::getInstance($name);
                         if ($upload) {
                             try {
                                 $file = $upload->getFile();
                                 $dir = Plugin::get('main')->getPublicUserfilesDir();
                                 if (!is_dir($dir)) {
                                     mkdir($dir, 0755);
                                 }
                                 if ($name == 'favicon') {
                                     $basename = uniqid() . '.ico';
                                     $generator = new \PHPICO($file->tmpFile, array(array(16, 16), array(32, 32), array(48, 48), array(64, 64)));
                                     $generator->save_ico($dir . $basename);
                                 } else {
                                     $basename = uniqid() . '.' . $file->extension;
                                     $upload->move($file, $dir, $basename);
                                 }
                                 // remove the old image
                                 @unlink($dir . Option::get("main.{$name}"));
                                 App::logger()->error("Option name = " . $name);
                                 App::logger()->error("main.{$name}");
                                 App::logger()->error("basename=" . $basename);
                                 Option::set("main.{$name}", $basename);
                             } catch (ImageException $e) {
                                 $form->error($name, Lang::get('form.image-format'));
                                 throw $e;
                             }
                         }
                     }
                 }
                 // Register the favicon
                 App::logger()->info('The options of the application has been updated by ' . App::session()->getUser()->username);
                 return $form->response(Form::STATUS_SUCCESS, Lang::get('admin.settings-save-success'));
             }
         } catch (Exception $e) {
             App::logger()->error('An error occured while updating application options');
             return $form->response(Form::STATUS_ERROR, DEBUG_MODE ? $e->getMessage() : Lang::get('admin.settings-save-error'));
         }
     }
 }
Example #28
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');
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 #29
0
 /**
  * 根据角色获取能操作的actions
  * 用于放在页面顶部作为快捷链接
  */
 public static function getQuickLinks()
 {
     static $links = null;
     if (!is_null($links)) {
         return $links;
     }
     //操作者权限
     $_authes = \App::session('auth', 'operator');
     if (!is_array($_authes)) {
         return $links;
     }
     //当前操作者在当前app下的权限
     $_authes = self::getAuthoriesByAppname($_authes, APP_NAME);
     $links = [];
     //将允许的控制器和方法放入数组
     $allowed_actions = [];
     foreach ($_authes as $controller => $actions) {
         $_controller = ucfirst($controller) . 'Controller';
         //控制器的actions
         $_actions = $_controller::actions();
         if (!$_actions) {
             continue;
         }
         $allowed_controller_actions = [];
         foreach ($actions as $action) {
             $allowed_controller_actions = array_merge($allowed_controller_actions, $_actions[$action]);
         }
         $allowed_actions[$controller] = $allowed_controller_actions;
     }
     $_exists = [];
     if (!empty($allowed_actions)) {
         foreach ($allowed_actions as $controller => $actions) {
             foreach ($actions as $action => $text) {
                 if (is_null($text)) {
                     continue;
                 }
                 if (is_array($text) and $text['link'] and !in_array($text['text'], $_exists)) {
                     $action == 'index' and $action = '';
                     $links[] = ['url' => \Func\url("{$controller}/{$action}"), 'text' => $text['text']];
                     $_exists[] = $text['text'];
                 }
             }
         }
     }
     return $links;
 }