Example #1
0
 public function getFake($uri, $domain = false, $get = false, $post = false, $method = false)
 {
     $request = new self();
     $request->uri = $request->cleanUri($uri);
     $request->host = $domain ? $domain : $_SERVER["HTTP_HOST"];
     $request->post = $post ? $post : self::$currentInstance->escapeVarsArray($_POST);
     $request->get = $get ? $get : self::$currentInstance->escapeVarsArray($_GET);
     return $request;
 }
 /**
  * Проверяет почту на уникальность
  */
 function service_mail_is_unique()
 {
     $mail = _Core_Request::getCurrent()->post['mail'];
     if ($this->model->checkServiceEmailIsUnique($mail)) {
         $this->tpl->assign('result', array('text' => 'Имя ящика уникально'));
     } else {
         $this->tpl->assign('error', array('text' => 'Имя ящика не уникально'));
     }
 }
 static function login($templateEngine)
 {
     // Получаем субдомен, если он есть
     $subdomain = array_shift(explode('.', _Core_Request::getCurrent()->host));
     $filename = dirname(__FILE__) . '/IframeLogin' . ucfirst(strtolower($subdomain)) . '.php';
     $classname = "Helper_IframeLogin" . ucfirst(strtolower($subdomain));
     if (file_exists($filename)) {
         $class = new $classname($templateEngine);
         $class->init();
     }
 }
 /**
  * Индексная страница
  * @param array $args  mixed
  * @return void
  */
 function index($args)
 {
     if (!session_id()) {
         session_start();
     }
     $user = Core::getInstance()->user;
     // Обьект запроса
     $request = _Core_Request::getCurrent();
     $errorMessage = null;
     // Проверка заполненности формы логина
     if (!isset($request->post['login']) || !isset($request->post['pass']) || empty($request->post['pass']) || empty($request->post['pass'])) {
         $errorMessage = 'Заполните, пожалуйста, все поля формы!';
     } else {
         // Подготавливаем переменную
         $login = htmlspecialchars($request->post['login']);
         $pass = sha1($request->post['pass']);
         if (!$user->initUser($login, $pass)) {
             $errorMessage = 'Некорректный логин или пароль!';
         }
     }
     // Ошибка передаётся в шаблон только при POST запросе
     if ($request->method != 'POST') {
         $this->tpl->assign('errorMessage', null);
     } else {
         $this->tpl->assign('errorMessage', $errorMessage);
     }
     if (!$errorMessage) {
         $this->model->login($login, $pass, @$_POST['autoLogin']);
     }
     if (isset($_POST['responseMode']) && $_POST['responseMode'] == 'json') {
         if (!$errorMessage) {
             die(json_encode(array('result' => array('text' => 'Login success!'))));
         } else {
             die(json_encode(array('error' => array('text' => $errorMessage))));
         }
     } else {
         if (!$errorMessage) {
             Core::getInstance()->tryRedirectToStartPage(true);
         }
     }
     // Если демо режим - всегда показываем Гид
     if (IS_DEMO) {
         setCookie("guide", "uyjsdhf", 0, COOKIE_PATH, COOKIE_DOMEN, false);
     }
     if (IS_DEMO && !Core::getInstance()->user->getId()) {
         $this->model->authDemoUser();
     }
 }
 /**
  * Регистрируем нового пользователя с азбуки финансов
  */
 private function _azbuka_registration()
 {
     $login = _Core_Request::getCurrent()->get['login'];
     $mail = _Core_Request::getCurrent()->get['mail'];
     // Генерируем нового пользователя на основе логина и его почты
     $newId = Login_Model::generateUserByAzbukaLogin($login, $mail);
     $row_user = Login_Model::getUserDataByID($newId);
     // @FIXME Непонятно что тут делает этот блок..
     // Если мы только что сделали сами пользователя, то мы и знаем его логин, нет?
     if (substr($row_user['user_login'], 0, 6) != 'azbuka') {
         $this->_redirect('/notfound', false, 404);
     }
     $uar = array('user_id' => $newId, 'user_name' => $row_user['user_login'], 'user_type' => 0);
     $this->templateEngine->assign('user_info', $uar);
     $this->templateEngine->assign('template_view', 'iframe');
     $this->_setCookie($row_user['user_login'], $row_user['user_pass']);
     $this->_redirect("Location: " . URL_ROOT_IFRAME . "info/");
     return $newId;
 }
 function edit($args)
 {
     throw new Exception('Look at ticket #1527');
     if (_Core_Request::getCurrent()->method == 'POST') {
         $params = $_POST;
         isset($params['id']) ? 1 : ($pda = 1);
         isset($params['id']) ? 1 : ($params['id'] = $args[0]);
         $account = Account::load($params);
         if (!$account->update($this->user, $params)) {
             $this->tpl->assign('error', array('text' => 'Счёт не удалён'));
         }
         $this->tpl->assign('result', array('text' => 'Счёт успешно изменён'));
         $this->tpl->assign('name_page', 'info_panel/info_panel');
     } else {
         $acm = new Account_Model();
         $acc = $acm->getAccountPdaInformation($args[0]);
         $this->tpl->assign('acc', $acc);
         $this->tpl->assign('name_page', 'account/edit');
     }
 }
Example #7
0
 public static function redirect($url, $isExternal = false, $statusCode = 200)
 {
     if (array_key_exists($statusCode, self::$headerByCode)) {
         header(self::$headerByCode[$statusCode]);
     }
     if ($isExternal) {
         header('Location: ' . $url);
         exit;
     }
     $request = _Core_Request::getFake($url);
     $router = new _Core_Router($request, _Core_TemplateEngine::getPrepared($request));
     try {
         $router->performRequest();
     } catch (Exception $e) {
         // Вывод отладочной информации
         if (DEBUG) {
             echo highlight_string("<?php\n" . $e->getTraceAsString());
             exit;
         } elseif ('/notfound' == $url) {
             exit;
         } else {
             self::redirect('/notfound', false, 404);
         }
     }
 }
 public function getStartUri()
 {
     //мобильную версию разберем отдельно
     if (_Core_Request::getCurrent()->host . '/' != HOST_ROOT_PDA) {
         // Если у нас есть неподтверждённые операции, то переходим на них
         if (count($this->getUserEvents('overdue')) > 0) {
             $startUri = '/calendar/#list';
         } else {
             //если есть счета, перейдем на самый первый счет
             $keys = array_keys($this->user_account);
             if (count($keys) > 0) {
                 $startUri = '/operation/#account=' . $keys[0];
             } else {
                 $startUri = '/info';
             }
         }
     } else {
         $startUri = '/operation/add/waste/';
     }
     return $startUri;
 }
 /**
  * Срабатывает при перетаскивании события
  * @return void
  */
 function edit_date()
 {
     $id = (int) _Core_Request::getCurrent()->post['id'];
     $date = Helper_Date::RusDate2Mysql(_Core_Request::getCurrent()->post['date']);
     $calendar = new Calendar(Core::getInstance()->user);
     if ($calendar->editDate($id, $date)) {
         $this->tpl->assign('result', array('text' => 'Операция успешно изменена'));
     } else {
         $this->tpl->assign('error', array('text' => implode(",\n", $calendar->getErrors())));
     }
     // @FIXME Перенести этот блок кода в календарь
     Core::getInstance()->user->initUserEvents();
     Core::getInstance()->user->save();
 }
 /**
  * Редактирует событие
  * @param $args array mixed Какие-нибудь аргументы
  * @return void
  */
 function edit(array $args = array())
 {
     //тип редактируемой операции
     $operationId = 0;
     $operation = array();
     if (array_key_exists(0, $args) && is_numeric($args[0]) && $args[0]) {
         $operationId = (int) $args[0];
     } elseif (isset($this->request->post['id']) && $this->request->post['id']) {
         $operationId = $this->request->post['id'];
     }
     // Получаем данные по редактируемой операции (а если нет ид, то и даных фиг..)
     if ($operationId) {
         $operation = $this->model->getOperation(Core::getInstance()->user->getId(), $operationId);
         $initType = $operation['type'];
     } else {
         $operation = array();
     }
     if (_Core_Request::getCurrent()->method == 'POST') {
         // Определяем массив данных для обработки
         $operation = array('id' => $operationId, 'type' => isset($this->request->post['type']) ? $this->request->post['type'] : $operation['type'], 'account' => $this->request->post['account'], 'amount' => $this->request->post['amount'], 'category' => isset($this->request->post['category']) ? $this->request->post['category'] : null, 'date' => null, 'comment' => isset($this->request->post['comment']) ? $this->request->post['comment'] : '', 'tags' => isset($this->request->post['tags']) ? $this->request->post['tags'] : $operation['tags'], 'convert' => isset($this->request->post['convert']) ? $this->request->post['convert'] : array(), 'close' => isset($this->request->post['close']) ? $this->request->post['close'] : array(), 'currency' => isset($this->request->post['currency']) ? $this->request->post['currency'] : array(), 'toAccount' => isset($this->request->post['toAccount']) ? $this->request->post['toAccount'] : null, 'target' => isset($this->request->post['target']) ? $this->request->post['target'] : null, 'accepted' => isset($this->request->post['accepted']) ? (int) $this->request->post['accepted'] : 1);
         // Если дата передана массивом (PDA) ...
         if (is_array($this->request->post['date'])) {
             $operation['date'] = $this->request->post['date']['day'] . '.' . $this->request->post['date']['month'] . '.' . $this->request->post['date']['year'];
         } elseif (empty($this->request->post['date'])) {
             $operation['date'] = date("d.m.Y");
         } else {
             $operation['date'] = $this->request->post['date'];
         }
         $operation = $this->model->checkData($operation);
         if (is_null($operation['type'])) {
             $this->model->errorData['id'] = 'Не удалось изменить операцию';
         }
         // Если нет ошибок - проводим операцию
         if (count($this->model->errorData) == 0) {
             //если изменили тип операции
             if ($operation['type'] != $initType) {
                 if ($initType == Operation::TYPE_TARGET) {
                     $this->model->deleteTargetOperation($operation['id']);
                 } else {
                     $this->model->deleteOperation($operation['id']);
                 }
                 //удалили операцию. вот теперь создадим новую
                 switch ($operation['type']) {
                     //Расход
                     case Operation::TYPE_WASTE:
                         $operation['amount'] = abs($operation['amount']) * -1;
                         $this->model->add($operation['type'], $operation['amount'], $operation['date'], $operation['category'], $operation['comment'], $operation['account'], $operation['tags']);
                         break;
                         // Доход
                     // Доход
                     case Operation::TYPE_PROFIT:
                         $this->model->add($operation['type'], $operation['amount'], $operation['date'], $operation['category'], $operation['comment'], $operation['account'], $operation['tags']);
                         break;
                         // Перевод со счёта
                     // Перевод со счёта
                     case Operation::TYPE_TRANSFER:
                         $operation['category'] = -1;
                         $this->model->addTransfer($operation['amount'], $operation['convert'], $operation['currency'], $operation['date'], $operation['account'], $operation['toAccount'], $operation['comment'], $operation['tags']);
                         break;
                         // Перевод на финансовую цель
                     // Перевод на финансовую цель
                     case Operation::TYPE_TARGET:
                         $target = new Targets_Model();
                         $target->addTargetOperation($operation['account'], $operation['target'], $operation['amount'], $operation['comment'], $operation['date'], $operation['close']);
                         //@FIXME Сделать автоматическое получение нового списка операций, при удачном добавлении
                         //exit(json_encode($target->getLastList(0, 100)));
                         break;
                 }
             }
             // а иначе редактируем по старому, конкретную операцию
             switch ($operation['type']) {
                 case Operation::TYPE_WASTE:
                     //Расход
                     $operation['amount'] = abs($operation['amount']) * -1;
                     $this->model->edit($operation['type'], $operation['id'], $operation['amount'], $operation['date'], $operation['category'], $operation['comment'], $operation['account'], $operation['tags']);
                     break;
                 case Operation::TYPE_PROFIT:
                     //Доход
                     $operation['amount'] = abs($operation['amount']);
                     $this->model->edit($operation['type'], $operation['id'], $operation['amount'], $operation['date'], $operation['category'], $operation['comment'], $operation['account'], $operation['tags']);
                     break;
                 case Operation::TYPE_TRANSFER:
                     // Перевод со счёта
                     $operation['category'] = null;
                     $this->model->editTransfer($operation['id'], $operation['amount'], $operation['convert'], $operation['date'], $operation['account'], $operation['toAccount'], $operation['comment'], $operation['tags']);
                     break;
                 case Operation::TYPE_TARGET:
                     // Перевод на финансовую цель см. в модуле фин.цели
                     $target = new Targets_Model();
                     $target->editTargetOperation($operation['id'], $operation['amount'], $operation['date'], $operation['target'], $operation['account'], $operation['comment'], $operation['close']);
                     break;
             }
             // #856. fixed by Jet. выводим разные сообщения для обычной и PDA версии
             $text = '';
             if (_Core_TemplateEngine::getResponseMode($this->request) == "json") {
                 $text = "Операция успешно изменена.";
             } else {
                 $text = "Операция успешно изменена. <a href='/operation/last'>последние операции</a>";
             }
             $this->tpl->assign('result', array('text' => $text));
         } else {
             $this->tpl->assign('error', array('text' => implode(" \n", $this->model->errorData)));
         }
     }
     // Переделываем дату изменённую в checkData для вставки в mysql обратно в человеческий вид
     $operation['date'] = date('d.m.Y', strtotime($operation['date']));
     $this->tpl->assign('operation', $operation);
     $this->tpl->assign('name_page', 'operations/edit');
 }
Example #11
0
$templateEngine = _Core_TemplateEngine::getPrepared($request);
// Запускаем хелпер для IFRAME авторизации и подключения шаблонов
Helper_IframeLogin::login($templateEngine);
// Инициализация роутера
$router = new _Core_Router($request, $templateEngine);
try {
    // Выполнение запроса (разбор ->вызов контроллера)
    $router->performRequest();
    if (_Core_Request::getCurrent()->host . '/' == HOST_ROOT_IFRAME) {
        $templateEngine->display('iframe/index.iframe.html');
    } elseif (_Core_Request::getCurrent()->host . '/' == HOST_ROOT_RAMBLER) {
        $templateEngine->display('index.html');
    } else {
        if (!IS_DEMO) {
            // Если пользователь зашёл с мобильного браузера
            if (_Core_Request::getCurrent()->host . '/' != HOST_ROOT_PDA && Helper_DetectBrowser::detectMobile() && !isset($_COOKIE['DO_WHANT_FULL_VERSION'])) {
                if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], HOST_ROOT_PDA) === false) {
                    header('Location: ' . URL_ROOT_PDA);
                    exit;
                } else {
                    setcookie('DO_WHANT_FULL_VERSION', true);
                }
            }
        }
        $templateEngine->display('index.html');
    }
    // Применение модификаций\удалений моделей
    _Core_ObjectWatcher::getInstance()->performOperations();
} catch (Exception $e) {
    // Вывод отладочной информации
    if (DEBUG) {