Пример #1
0
 /**
  * Constructor
  */
 public function __construct($rootPath, $configPath)
 {
     if (!self::$instance) {
         self::$instance = $this;
         if (file_exists($configPath)) {
             $this->options = parse_ini_file($configPath, true);
         } else {
             throw new Exception('Config file not found.');
         }
         if (!empty($this->options['Application']) && !empty($this->options['Application']['bootstrap'])) {
             $bootsPath = str_replace('[APP_PATH]', APP_PATH, $this->options['Application']['bootstrap']);
             if (file_exists($bootsPath)) {
                 require_once $bootsPath;
             } else {
                 echo 'Bootstrap not found. ' . $bootsPath;
             }
         }
         if (is_dir($rootPath)) {
             self::$root = $rootPath;
         } else {
             throw new Exception('Root dir not found.');
         }
         K_Request::init();
     } else {
         return self::instance;
     }
 }
Пример #2
0
 public function dispatch()
 {
     $this->route = K_Request::route();
     $this->bootstrap->route = $this->route;
     $this->route['caller'] = 0;
     // 0 - call from internet request, 1 - call local
     $this->executeRequest($this->route);
 }
Пример #3
0
 public function moveAction()
 {
     $result = K_Request::call(array('module' => 'admin', 'controller' => 'tree', 'action' => 'move', 'params' => array()));
     json_decode($result, true);
     if ($result['status']) {
         $jsonReturn['error'] = false;
         $jsonReturn['msg'] = 'Блог успешно перемещен.';
         $jsonReturn['form'] = false;
     } else {
         $jsonReturn['error'] = true;
         $jsonReturn['msg'] = array('1' => array('label' => 'Раздел', 'error' => 'неправильнный раздел для новости'));
     }
     $this->putJSON($jsonReturn);
 }
Пример #4
0
 public static function route()
 {
     if (!count(self::$rewriteList)) {
         self::$rewriteList[] = new K_Request_Router();
     }
     $result;
     foreach (self::$rewriteList as $router) {
         if ($result = $router->assemble()) {
             self::$params = isset($result['params']) ? $result['params'] : null;
             $result['params'] =& self::$params;
             return $result;
         }
     }
     return null;
 }
Пример #5
0
 /**
  * Inline exception handler, displays the error message, source of the
  * exception, and the stack trace of the error.
  *
  * @uses    Exception_Exception::text
  * @param   object   exception object
  * @return  boolean
  */
 public static function handler(exception $e)
 {
     try {
         // устанавливаем ошибку в контроллер, что бы не рендерил представление
         K_Controller::setError();
         // Get the exception information
         $type = get_class($e);
         $code = $e->getCode();
         $message = $e->getMessage();
         $file = $e->getFile();
         $line = $e->getLine();
         // Get the exception backtrace
         $trace = $e->getTrace();
         if ($e instanceof ErrorException) {
             if (isset(K_Exception::$php_errors[$code])) {
                 // Use the human-readable error name
                 $code = K_Exception::$php_errors[$code];
             }
         }
         // Create a text version of the exception
         $error = K_Exception::text($e);
         if (K_Request::isAjax() === true) {
             // Just display the text of the exception
             echo "\n{$error}\n";
             // добовляем ошибку в логгер и дебагер
             K_Log::get()->add($error);
             K_Debug::get()->add($error, $trace);
             exit(1);
         }
         echo "\n{$error}\n";
         // добовляем ошибку в логгер и дебагер
         K_Log::get()->add($error);
         K_Debug::get()->addError($error, $trace);
         exit(1);
     } catch (exception $e) {
         // Clean the output buffer if one exists
         ob_get_level() and ob_clean();
         // Display the exception text
         echo K_Exception::text($e), "\n";
         // Exit with an error status
         exit(1);
     }
 }
Пример #6
0
 public function saveAction()
 {
     if (!K_Request::isPost()) {
         $this->putAjax('ERROR');
     }
     if (!K_Auth::isLogin()) {
         $this->putAjax('ERROR');
     }
     $validate = array('user_password' => array('required' => true, 'userTruePass'), 'user_email' => array('required' => true, 'lengthTest', 'email', 'userExists'));
     $userSettings = new Admin_Model_UserSettings();
     $oldPassword = K_Arr::get($_POST, 'oldpassword', '');
     $data = array('user_password' => trim($_POST['user_password']), 'user_email' => trim($_POST['user_email']), 'password1' => trim($_POST['password1']), 'password2' => trim($_POST['password2']));
     if (strlen($data['password1']) > 0 || strlen($data['password2']) > 0) {
         $validate['password1'] = array('required' => true, 'pwdTest');
     }
     if ($userSettings->isValidRow($data, $validate)) {
         unset($data['user_password']);
         if (strlen($data['password1']) > 0) {
             $data['user_password'] = md5(md5($data['password1'] . K_Registry::get('Configure.salt')));
         }
         unset($data['password1']);
         unset($data['password2']);
         /*  if (! strlen($data['user_email']) > 0) {
                 unset($data['user_email']);
             }*/
         if (count($data)) {
             $data['user_id'] = K_Auth::getUserInfo('user_id');
             $userSettings->save($data);
             K_Auth::mergeUserInfo($data);
         }
         $returnJson['error'] = false;
         $returnJson['msg'] = "<strong>OK:</strong>Настройки удачно сохранены";
     } else {
         $returnJson['error'] = true;
         $returnJson['msg'] = $userSettings->getErrorsD($this->dictionary);
     }
     $this->putJSON($returnJson);
 }
Пример #7
0
 public function logoutAction()
 {
     K_Auth::logout();
     K_Request::redirect("/admin/auth");
 }
Пример #8
0
 /** @method B initRouter() Инициализация роутера, описание роутеров находиться в конфигах
  * 
  */
 public function initRouter()
 {
     require_once ROOT_PATH . '/configs/routers/IndexRouter.php';
     require_once ROOT_PATH . '/configs/routers/FrontendRouter.php';
     //K_Request::addRewriteRule( new IndexRouter() ); // set index router
     K_Request::addRewriteRule(new FrontendRouter());
     // set index router
     K_Request::addRewriteRule(new K_Request_Router());
 }
Пример #9
0
 public static function accessSite($res, $privilege = 'view')
 {
     $access = self::accessSiteCheck($res, $privilege);
     if (!$access) {
         if (isset(self::$lastKnowResourse)) {
             $denyAction = K_Access::acl()->getDeneyAction(self::$lastKnowResourse);
             if ($denyAction) {
                 if ($resourse != $denyAction) {
                     K_Request::redirect($denyAction);
                 }
             } else {
                 if ($resourse != 'default/index/index') {
                     K_Request::redirect('/');
                 }
             }
         } else {
             if ($resourse != 'default/index/index') {
                 K_Request::redirect('/');
             }
         }
     }
 }
Пример #10
0
 protected function saveAction()
 {
     if (!K_Request::isPost()) {
         //ошибка
         $this->putAjax("ERROR");
     }
     $typeClientForm = new Admin_Model_ClientForm();
     //загружаем данные формы
     $formData = Gcontroller::loadclientFormStructure(trim($_POST['tree_link']));
     /*    $clientFormData = $typeClientForm->fetchRow( K_Db_Select::create()->where( "type_clientform_id=$clientFormKey" ) );
           $this->view->formStructure=unserialize( $clientFormData['type_clientform_content'] );*/
     $formStructure = json_decode($formData['form_structure']);
     $formStructure = K_Tree_Types::objectToArray($formStructure);
     foreach ($formStructure as $v) {
         if ($v['type'] == 'xform') {
             //сохраняем дополнительный настройки
             $Xform = $v['values'];
         } else {
             // сохраним ключи полей, что-бы сохранять в базу только то что надо.
             $formFields[] = $v['values']['name'];
             if (isset($v['values']['name']) && isset($v['vlds'])) {
                 $name = $v['values']['name'];
                 $nameAccos[$name] = $v['values']['label'];
                 $vlds = $v['vlds'];
                 $fieldVlds = array();
                 foreach ($vlds as $vld) {
                     if ($vld == "requred") {
                         $fieldVlds['requred'] = true;
                     } else {
                         $fieldVlds[] = $vld;
                     }
                 }
                 $validate[$name] = $fieldVlds;
             }
         }
     }
     // выбираем из поста только нужные поля
     foreach ($_POST as $k => $v) {
         if (in_array($k, $formFields)) {
             if (is_string($v)) {
                 $data[$k] = trim($v);
             }
             $data[$k] = $v;
         }
     }
     if ($typeClientForm->isValidRow($data, $validate)) {
         $clientFormData = new Admin_Model_ClientFormData();
         $saveDate = array('clientform_data_type' => trim($_POST['tree_link']), 'clientform_data_content' => serialize($data));
         // сахроняем форму и отправляем письма.
         if ($Xform['ck_save_db']) {
             $clientFormData->save($saveDate);
         }
         $render = new K_TemplateRender();
         $render->setTags($data);
         $mailer = new K_Mail();
         if (isset($Xform['ck_admin_email']) && $Xform['admin_mail_tmp'] && $Xform['admin_email']) {
             //Отправляем письмо на емеил админа
             $mailText = $render->assemble($Xform['admin_mail_tmp']);
             $mailer->setBody($mailText);
             $mailer->addTo($Xform['admin_email']);
             $mailer->send('*****@*****.**', 'Ползователь заполнил форму');
         }
         //  echo $data['ck_client_email'].'    '.$Xform['ck_client_email'].' '.$Xform['client_email_field_name'].'  '.$Xform['client_mail_tmp'];
         if (isset($Xform['client_email_ck_name']) && $Xform['client_email_ck_name']) {
             $clientEmailCkName = $Xform['client_email_ck_name'];
         }
         // echo $data[$clientEmailCkName].'    '.$Xform['ck_client_email'].' '.$Xform['client_email_field_name'].'  '.$Xform['client_mail_tmp'];
         if (isset($data[$clientEmailCkName]) && isset($Xform['ck_client_email']) && isset($Xform['client_email_field_name']) && isset($Xform['client_mail_tmp'])) {
             $clientEmailFieldName = $Xform['client_email_field_name'];
             if (isset($data[$clientEmailFieldName])) {
                 //Отправляем письмо на емеил пользователя
                 $mailText = $render->assemble($Xform['client_mail_tmp']);
                 $mailer->setBody($mailText);
                 $mailer->addTo($data[$clientEmailFieldName]);
                 $mailer->send('*****@*****.**', 'Ваша форма удачно отправленна');
             }
         }
         $jsonReturn['error'] = false;
         $jsonReturn['msg'] = '<strong>ОК:<strong> Форма удачно отправлена';
     } else {
         $jsonReturn['error'] = true;
         $jsonReturn['msg'] = $typeClientForm->getErrorsD($nameAccos);
     }
     if (K_Request::isAjax()) {
         $this->putJSON($jsonReturn);
     } else {
         $this->putAjax("ERROR");
     }
     //
     /*else{
       if($jsonReturn['error'] = false){
       
       //заготовка на случай если js отключен
       //загрузка промежуточного шаблона с выводом ошибок и формой для продолжения заполнения 
       
       
       }  
       else{
       // промежуточный шаблон с нотификацией о правильном заполнении и редирект туда от куда пришол пользователь.    
       
       
       }
       
       }*/
 }
Пример #11
0
 public function exporttypeAction()
 {
     $typeId = $this->getParam('typeid');
     $typeModel = new Admin_Model_Type();
     $typeRow = $typeModel->fetchRow(K_Db_Select::create()->where(array('type_id' => $typeId)));
     $typeRow = $typeRow->toArray();
     $typeName = $typeRow['type_name'];
     $configArray = array('typeName' => $typeName);
     $query = new K_Db_Query();
     $typeTable = $query->q('SHOW CREATE TABLE type_' . $typeName . ';');
     $zip = new ZipArchive();
     //создаём папку если такой нет.
     if (!file_exists(ROOT_PATH . '/cache/typestmp/')) {
         mkdir(ROOT_PATH . '/cache/temp/', 0777, true);
     }
     if ($zip->open(ROOT_PATH . '/www/upload/typestmp/' . $typeName . '.zip', ZipArchive::CREATE) === true) {
         // php файлы
         $zip->addFile(ROOT_PATH . '/application/type/model/' . $typeName . '.php', $typeName . '_model.php');
         /// Добавление модели типа
         $zip->addFile(ROOT_PATH . '/application/type/controller/' . $typeName . '.php', $typeName . '_controller.php');
         /// Добавление контроллера типа
         $zip->addFile(ROOT_PATH . '/application/admin/controller/gui/' . $typeName . '.php', $typeName . '_gui.php');
         /// Добавление GUI типа
         // иконка
         $zip->addFile(ROOT_PATH . '/www/adm/img/tree/' . $typeName . '.png', $typeName . '.png');
         /// Добавление иконки типа
         // данные
         $zip->addFromString('config.json', json_encode($configArray));
         // конфигурационный файл
         $zip->addFromString('typerow.json', json_encode($typeRow));
         // строка типа из таблицы типов
         $zip->addFromString('typetable.sql', $typeTable[0]['Create Table']);
         // структура таблицы типа
         $zip->close();
     } else {
         echo 'Не могу создать архив!';
     }
     K_Request::redirect('/upload/typestmp/' . $typeName . '.zip');
 }
Пример #12
0
 /** Методы блоков
  *  подключает html шаблоны блоков
  *
  *
  */
 private function bd_simpleTypeBlock($node)
 {
     $result = '';
     if (is_dir(APP_PATH . '/blocks/' . $node['tree_type'])) {
         include APP_PATH . '/blocks/' . $node['tree_type'] . '/item.phtml';
     }
     return K_Request::call(array('module' => 'typebloks', 'controller' => $node['tree_type'], 'action' => 'item', 'params' => array('node' => $node)));
 }