function work(Request $request) { // Объект по URI запроса $obj = Data::read('/contents' . $request['REQUEST']['path']); $request->mix(['REQUEST' => ['object' => $obj]]); return parent::work($request); }
function work(Request $request) { $user = Auth::get_user(); if ($user->is_exists()) { if (!$user->confirm->is_draft()) { //новый и еще неактивный $this->_result = 5; } else { //Есть такой активный пользователь $this->_result = 4; } //пользователя еще нет } else { if ($request['REQUEST']['form']) { //Присвоим email новому пользователю и проверим уникальность $user->email->value($request['REQUEST']['email']); if ($request['REQUEST']['call'] == 'check') { if (!$user->check()) { if ($user->errors()->email->value->duplicate) { $this->_result = 2; } else { //Другая ошибка $this->_result = 3; } } else { //все корректно $this->_result = 1; } $session['result'] = $this->_result; Session::set('form', array($this->uri() . $this->getToken() => $session)); setcookie('token', $this->getToken(), 0, '/'); return $session; } else { if (isset($request['COOKIE']['token']) && Session::is_exist('form')) { $form = Session::get('form'); if (isset($form[$this->uri() . $request['COOKIE']['token']])) { $form = $form[$this->uri() . $request['COOKIE']['token']]; Session::remove('form'); } if (isset($form['result'])) { $this->_result = $form['result']; } } if ($this->_result == 1 && isset($user)) { $user->password->value($request['REQUEST']['password']); $user->title->value($request['REQUEST']['email']); $user->confirm->proto("/vendor/boolive/basic/string"); $user->confirm->value(uniqid('', true)); Data::write($user); //Теперь у нас есть такой пользователь $this->_result = 5; $this->mailSender->sendMail($to = $user->email->value(), $subject = 'Подтвержление регистрации на ' . $this->mailSender->domain->value(), $message = 'Здравствйте, вы зарегистрировались на ' . $this->mailSender->domain->value() . ' , для подтверждения актуальности электронного адреса, перейдите, пожалуйста по <a href="' . $this->mailSender->domain->value() . '/profile?confirm=' . $user->confirm->value() . '">ссылке</a>'); $request->redirect('profile?confirm=0'); } } } } return parent::work($request); }
function show($v, Request $request) { $v['active'] = $request['REQUEST']['object']->uri(); $v['items'] = Data::find(['from' => '', 'select' => 'children', 'depth' => 1, 'order' => ['order', 'asc']]); $v['active'] = $request['REQUEST']['object']; // array_unshift($v['items'], Data::read('')); return parent::show($v, $request); }
function work(Request $request) { if (isset($request['REQUEST']['proto'])) { $request['REQUEST']['parent'] = $request['REQUEST']['object']; $request['REQUEST']['object'] = Data::create($request['REQUEST']['proto'], $request['REQUEST']['parent']); $request['REQUEST']['object']->complete(); } if (!empty($request['REQUEST']['attr']['name'])) { $request['REQUEST']['object']->name($request['REQUEST']['attr']['name']); } return parent::work($request); }
function getList(Request $request, &$cond = []) { $count_per_page = $this->count_per_page->is_exists() ? max(1, $this->count_per_page->value()) : 10; $cond['limit'] = [($request['REQUEST']['page'] - 1) * $count_per_page, $count_per_page]; $result = parent::getList($request, $cond); if (count($result) < $count_per_page) { $count = $request['REQUEST']['page']; } else { $count = ceil(Data::find(Data::unionCond(['calc' => 'count'], $cond)) / $count_per_page); } $request->mix(['REQUEST' => ['page_count' => $count]]); return $result; }
function checkChild(user $user) { self::$config = Config::read('auth'); $where = [['child', 'email', ['value', '=', $user->email->value()]]]; if ($user->is_exists()) { $where[] = ['uri', '!=', $user->uri()]; } $result = Data::find(array('from' => self::$config['users-list'], 'select' => 'children', 'depth' => 'max', 'where' => $where, 'key' => false, 'limit' => array(0, 1), 'comment' => 'search if user already exist'), false); if (!empty($result)) { $user->errors()->_children->email->_attributes->value->dublicate = 'Email не уникален'; return false; } else { return true; } }
function show($v, Request $request) { $v['active'] = $request['REQUEST']['object']->uri(); $from = trim($v['active'], '/ '); if ($from) { $paths = explode('/', $from); $from = ''; $cnt = min(1, count($paths)); for ($i = 0; $i < $cnt; $i++) { $from .= '/' . $paths[$i]; } $v['from'] = $from; $v['items'] = Data::find(['from' => $from, 'select' => 'children', 'depth' => 10, 'struct' => 'tree', 'order' => ['order', 'asc']]); } else { return false; } return parent::show($v, $request); }
/** * Функция, подтверждения корректрости электронного адреса пользователя * Находит его по уникальной последовательности в поле confirm и удаляет поле тем самым активируя пользователя * @param $confirm * @return integer результат операции, обработка результата в функции work */ private function confirmUser($confirm) { /** @var user $user */ $user = $this->searchUser($confirm); if ($user && !$user->confirm->is_draft()) { $user->confirm->is_draft(true); Data::write($user->confirm); //Успешное подтверждение $result = 1; } else { //Пользователь уже существует if ($user && $user->confirm->is_draft()) { $result = 4; } else { //Нет пользователя с таким значением - неизвестно почему $result = 3; } } return $result; }
function work(Request $request) { if ($request['REQUEST']['form']) { $session = array(); try { self::$config = Config::read('auth'); $result = Data::find(array('from' => self::$config['users-list'], 'select' => 'children', 'depth' => 'max', 'where' => array(['child', 'email', array('value', '=', $request['REQUEST']['email'])], ['child', 'password', array('value', '=', $request['REQUEST']['password'])]), 'key' => false, 'limit' => array(0, 1), 'comment' => 'sign-in user by email and password'), false); if (!empty($result)) { $user = $result[0]; Auth::set_user($user); if ($request['REQUEST']['remember-me']) { Auth::set_user($user, 1234565); } $request->redirect(self::$config['redirect']); } else { $this->_result = 0; } } catch (\Exception $error) { $this->_result = 0; } $session['result'] = $this->_result; Session::set('form', array($this->uri() . $this->getToken() => $session)); setcookie('token', $this->getToken(), 0, '/'); return $session; } else { // Отображение формы $v = array(); if (isset($request['COOKIE']['token']) && Session::is_exist('form')) { $form = Session::get('form'); if (isset($form[$this->uri() . $request['COOKIE']['token']])) { $form = $form[$this->uri() . $request['COOKIE']['token']]; Session::remove('form'); } if (isset($form['result'])) { $this->_result = $form['result']; } } $this->res->start($request); return $this->show($v, $request); } }
/** * Генерация события * * @param string $event Имя события * @param array|mixed $params Параметры события * @param bool $all * @return mixed Объект события с результатами его обработки */ static function trigger($event, $params = [], $all = true) { $result = []; if (isset(self::$handlers[$event])) { foreach (self::$handlers[$event] as $key => $handler) { if (isset($handler[0]) && (empty($handler[0]) || mb_strpos($handler[0], '/') !== false)) { $out = call_user_func_array([\boolive\core\data\Data::read($handler[0]), $handler[1]], $params); } else { $out = call_user_func_array($handler, $params); } if ($out === false) { if (!$all) { return $out; } } else { $result[$key] = $out; } } } if (count($result) == 0 && !$all) { return null; } return $result; }
/** @const string Директория временных файлов на сервере. Слеш в конце обязателен! */ define('DIR_TEMP', DIR . 'temp/'); /** @const string Директория конфигураций. Слеш в конце обязателен! */ define('DIR_CONFIG', DIR . 'config/'); // Адрес сайта, например: boolive.ru. Значение по умолчанию для CLI режима define('HTTP_HOST', empty($_SERVER['HTTP_HOST']) ? 'boolive.ru' : $_SERVER['HTTP_HOST']); /* Признак, выводить всю трассировку?*/ define('GLOBAL_TRACE', false); /* Признак, профилировать запросы к модулю даных?*/ define('PROFILE_DATA', false); // Get composer loader $loader = (include DIR . 'vendor/autoload.php'); // Activate Boolive Core::activate($loader); // Start project (read and call root object) echo Data::read('/interfaces')->start(new Request()); //$u = \boolive\core\auth\Auth::get_user(); //trace($u); //trace($u->password); //trace(Data::find([ // 'from' => '/access/users', // 'select' => 'children', // //'struct' => 'tree', // 'key'=>'name', // 'depth' => 10 //])); //$bench_cnt = 100; // //$test = 3; // ////$dir = 'C:/Server/Sites/usurt/';
function work(Request $request) { $uri = ''; // $s = C::read(); // C::writeln(mb_detect_encoding($s,['utf-8','cp866'])); do { try { C::write(C::style($uri, [C::COLOR_GRAY_DARK]) . '> '); $commands = preg_split('/\\s/ui', trim(C::read())); $cmd_count = count($commands); if ($commands[0] == 'show') { $new_uri = !empty($commands[1]) ? $uri . '/' . trim($commands[1], ' \\/') : $uri; $obj = Data::read($new_uri); C::writeln(C::style(Trace::format($obj, false))); } else { if (mb_strlen($commands[0]) > 1 && ($commands[0][0] == '/' || mb_substr($commands[0], 0, 2) == '..')) { $new_uri = !empty($commands[0]) ? $uri . '/' . trim($commands[0], ' \\/') : $uri; $obj = Data::read($new_uri, false, true); if ($obj && $obj->is_exists()) { $uri = $obj->uri(); } else { C::writeln(C::style('Object does not exist', C::COLOR_RED)); } } else { if ($commands[0] == 'ls' || $commands[0] == 'children') { $list = Data::find(['from' => $uri, 'select' => empty($commands[1]) || $commands[1] != '-p' ? 'children' : 'properties', 'struct' => 'list', 'limit' => [0, 50]]); foreach ($list as $obj) { C::writeln(C::style($obj->name(), C::COLOR_BLUE)); } } else { if (preg_match('/^\\s*select(\\(|=)/ui', $commands[0])) { $cond = Data::normalizeCond($commands[0], false); if (!isset($cond['from'])) { $cond['from'] = $uri; } $result = Data::find($cond); C::writeln(C::style(Trace::format($result, false))); } else { if ($commands[0] == 'color') { if (!empty($commands[1])) { C::use_style($commands[1] == 'off' ? false : null); } else { C::use_style(true); } } else { if ($cmd_count > 1 && $commands[0] == 'attr') { $obj = Data::read($uri); $attr = $commands[1]; if ($obj instanceof Entity && $obj->is_exists() && $obj->is_attr($attr)) { if ($cmd_count > 2) { if ($commands[2] === "null") { $commands[2] = null; } else { if ($commands[2] === "false") { $commands[2] = false; } else { $commands[2] = trim(trim($commands[2], '"')); } } $obj->{$attr}($commands[2]); Data::write($obj); C::writeln(Trace::format($obj, false)); } else { C::writeln(C::style($obj->attr($attr)), C::COLOR_PURPLE); } } } else { if ($cmd_count > 2 && $commands[0] == 'new') { $new_uri = !empty($commands[1]) ? $uri . '/' . trim($commands[1], ' \\/') : $uri; list($parent, $name) = F::splitRight('/', $new_uri); if (!$parent) { $parent = ''; } $proto = $commands[2]; $obj = Data::create($proto, $parent, ['name' => $name]); $signs = array_flip($commands); if (isset($signs['-m'])) { $obj->is_mandatory(true); } if (isset($signs['-p'])) { $obj->is_property(true); } if (isset($signs['-d'])) { $obj->is_draft(true); } if (isset($signs['-h'])) { $obj->is_hidden(true); } if (isset($signs['-l'])) { $obj->is_link(true); } if (isset($signs['-r'])) { $obj->is_relative(true); } $obj->complete(); Data::write($obj); C::writeln(Trace::format($obj, false)); } else { if ($commands[0] == 'complete') { $obj = Data::read($uri); $signs = array_flip($commands); $only_mandatory = !isset($signs['-all']) && !isset($signs['-not-mandatory']); $only_property = !isset($signs['-all']) && !isset($signs['-not-property']); $obj->complete($only_mandatory, $only_property); Data::write($obj); C::writeln(Trace::format($obj, false)); } else { C::writeln(C::style('Unknown command', C::COLOR_RED)); } } } } } } } } } catch (Error $e) { C::writeln(C::style($e->getMessage(), C::COLOR_RED)); } catch (\Exception $e) { C::writeln(C::style((string) $e, C::COLOR_RED)); } Buffer::clear(); } while ($commands[0] !== 'exit'); C::writeln("\nby!"); // if (!empty($request['ARG'][2])) { // if ($request['ARG'][2] == 'read') { // $uri = empty($request['ARG'][3]) ? '' : '/' . trim($request['ARG'][3], '/'); // $obj = Data::read($uri); // C::writeln(C::style(Trace::style($obj, false))); // } else // if ($request['ARG'][2] == 'find') { // $cond = empty($request['ARG'][3]) ? '' : trim($request['ARG'][3], '/'); // $result = Data::find($cond); // C::write(C::style(Trace::style($result, false))); // } else // if ($request['ARG'][2] == 'edit') { // $object = Data::read(empty($request['ARG'][3]) ? '' : '/'.trim($request['ARG'][3], '/')); // $attr = empty($request['ARG'][4]) ? null : $request['ARG'][4]; // $value = empty($request['ARG'][5]) ? null : $request['ARG'][5]; // if ($object instanceof Entity && $object->is_exists() && $attr){ // $object->{$attr}($value); // Data::write($object); // C::write(C::style(Trace::style($object, false))); // } // }else // { //// phpinfo(); //// C::writeln(Trace::style($_ENV, false)); //// C::writeln(getenv('ANSICON')); // C::writeln( // C::style(json_encode($request['ARG']), [C::STYLE_BOLD, C::STYLE_UNDERLINE, C::COLOR_BLUE])); // //$a = C::read(); // //C::writeln($a); // //// fwrite(STDOUT, $colors->getColoredString("Testing Colors class, this is purple string on yellow background.", "purple", "yellow") . "\n"); //// $line = fgets(STDIN); //// if(trim($line) != 'yes'){ //// echo "ABORTING!\n"; //// exit; //// } //// echo "\n"; //// echo "Thank you, continuing...\n"; //// return true; // } // } }
/** * Выбор дерева объектов для пунктов меню * @param array $cond Услвоие выборки * @return array|Entity|mixed|null */ function getItems($cond = array()) { // $is_list = $this->is->find(array('where'=>array('is_link','!=',0), 'group'=>true)); // foreach ($is_list as $key => $is){ // $is_list[$key] = $is->linked()->id(); // } $cond['select'] = 'children'; $cond['struct'] = 'tree'; //$cond['from'] = $request['REQUEST']['object']->linked(); //$cond['depth'] = array(1, 'max'); // выбрать из хранилища всё дерево меню $cond['where'] = array('all', array(array('attr', 'is_hidden', '=', 0), array('attr', 'is_draft', '=', 0), array('child', 'menu', ['value', '=', true]))); $cond['order'] = ['order', 'asc']; // $cond['group'] = true; // Для выбранных объектов выполнять подвыборки // $cond['cache'] = 2; // Кэшировать сущности $items = Data::find($cond); if ($cond['from']->menu->value()) { array_unshift($items, ['object' => $cond['from'], 'sub' => []]); } return $items; }
/** * Сохранение сущности * @param Entity $entity * @throws Error */ function write($entity) { // Если объект свойство, то сохранять родительский объект?? if ($entity->is_property()) { if ($parent = $entity->parent(null, true)) { $parent->__set($entity->name(), $entity); Data::write($parent); } } else { // Текущие сведения об объекте $info = []; if ($entity->is_exists()) { // Текущие сведения об объекта $uri = $entity->is_changed('uri') ? $entity->changes('uri') : $entity->uri(); if ($uri === '') { $file = DIR . 'project.info'; } else { $file = DIR . trim($uri, '/') . '/' . File::fileName($uri) . '.info'; } if (is_file($file)) { $info = file_get_contents($file); $info = json_decode($info, true); } } // Подбор уникального имени // @todo Перенос php файлов влечет за собой фатальные ошибки!!!! так как меняется namespace и class name if ($entity->is_changed('uri') || !$entity->is_exists()) { // Проверка уникальности нового имени путём создания папки // Если подбор уникального имени, то создавать пока не создаться (попробовать постфикс) $path = dirname($entity->dir(true)) . '/'; $name = $entity->name(); if ($new_path = File::makeUniqueDir($path, $name, 1, $entity->is_auto_namig())) { $entity->name(basename($new_path)); $info['name'] = $entity->name(); } else { $entity->errors()->_attributes->name->add(new Error('Не уникальное', 'unique')); throw $entity->errors(); } // Перемещение старой папки в новую if ($entity->is_exists()) { File::rename($entity->dir(true, true), $entity->dir(true, false)); } if ($entity->is_changed('name') && $entity->is_exists()) { // @todo Переименовать .info, .php и, возможно, привязанный файл. } // Обновить URI подчиненных объектов не фиксируя изменения $entity->updateChildrenUri(); } // Новые сведения об объекте $info_new = $this->export($entity, isset($info['properties']) ? $info['properties'] : [], function (Entity $entity, $file) { return Data::save_file($entity, $file); }); // Порядковый номер // 1. Подбор максимального среди существующих // 2. Смещение порядка у последующих объектов // Сохранить объект с свлйствами JSON $uri = $entity->uri(); if ($uri === '') { $file = DIR . 'project.info'; } else { $file = DIR . trim($uri, '/') . '/' . File::fileName($uri) . '.info'; } File::create(F::toJSON($info_new, true), $file); } // Сохранить подчиненные foreach ($entity->children() as $child) { /** @var Entity $child */ if (!$child->is_property()) { Data::write($child); } } }
function getCihildrenControllers($cond = [], Request $request) { $cond = Data::unionCond($cond, ['select' => 'children', 'from' => $this, 'order' => ['order', 'asc']]); return Data::find($cond); }
function process(Request $request) { Data::write($request['REQUEST']['object']); return true; }
function getList(Request $request, &$cond = []) { $cond = Data::unionCond($cond, ['from' => $request['REQUEST']['object'], 'select' => 'properties', 'depth' => 1, 'key' => 'name']); return Data::find($cond); }
/** * Условие поиска или валидации объекта * @param mixed $value Фильтруемое значение * @param null|Error &$error Возвращаемый объект исключения, если значение не соответсвует правилу * @param array $args Аргументы фильтра * @return string */ static function condition($value, &$error, $args) { $result = Data::normalizeCond($value); if ($result === null) { $error = new Error('Не является условием поиска', 'condition'); } return $result; }
static function fromArray($array) { if (isset($array['_attributes']['uri'])) { $obj = Data::read($array['_attributes']['uri']); } else { if (!isset($array['class'])) { $array['class'] = '\\boolive\\core\\data\\Entity'; } $obj = new $array['class'](); } if (!empty($array['_errors'])) { $obj->_errors = Error::createFromArray($array['_errors']); } if (isset($array['_children'])) { foreach ($array['_children'] as $key => $child) { $obj->_children[$key] = self::fromArray($child); $obj->_children[$key]->_parent = $obj; if ($obj->_children[$key]->_errors) { $obj->errors()->_children->add($obj->_children[$key]->_errors); } } } $obj->_attributes = $array['_attributes']; $obj->_changes = $array['_changes']; $obj->_checked = $array['_checked']; $obj->_auto_naming = $array['_auto_naming']; $obj->_is_inner = $array['_is_inner']; return $obj; }
function show($v, Request $request) { $v['parent'] = $request['REQUEST']['object']; $v['items'] = Data::find(['from' => '/library/contents', 'select' => 'children']); return parent::show($v, $request); }
function getList(Request $request, &$cond = []) { $cond = Data::unionCond($cond, ['from' => $request['REQUEST']['object'], 'select' => 'children', 'depth' => 1]); return Data::find($cond); }
static function entity($info) { $key = isset($info['uri']) ? $info['uri'] : null; if (!isset($key) || !($entity = Buffer::get_entity($key))) { try { $name = basename($info['uri']); if (isset($info['uri'])) { if (!empty($info['is_default_logic'])) { if (isset($info['proto'])) { // Класс от прототипа $class = get_class(self::read($info['proto'])); } else { // Класс наследуется, но нет прототипа $class = '\\boolive\\core\\data\\Entity'; } } else { if (empty($info['uri']) || preg_match('#^[a-zA-Z_0-9\\/]+$#ui', $info['uri'])) { $namespace = str_replace('/', '\\', rtrim($info['uri'], '/')); // Свой класс if (empty($namespace)) { $class = '\\project'; } else { if (substr($namespace, 0, 7) === '\\vendor') { $class = substr($namespace, 7) . '\\' . $name; } else { $class = $namespace . '\\' . $name; } } } else { $class = '\\boolive\\core\\data\\Entity'; } } } else { $class = '\\boolive\\core\\data\\Entity'; } if (isset($info['value']) && !isset($info['is_default_value'])) { $info['is_default_value'] = false; } if (!isset($info['is_default_value'])) { $info['is_default_value'] = true; } if (!isset($info['value']) && !empty($info['is_default_value']) && !empty($info['proto'])) { $info['value'] = Data::read($info['proto'])->value(); } // if (!isset($info['is_mandatory']) && isset($info['proto'])){ // $proto = self::read($info['proto']); // $info['is_mandatory'] = $proto->is_mandatory(); // } $entity = new $class($info); } catch (\ErrorException $e) { $entity = new Entity($info); } if (isset($key)) { Buffer::set_entity($entity); } } return $entity; }
/** * Создание идентификатора для указанного URI. * Если объект с указанным URI существует, то будет возвращен его идентификатор * @param string $uri URI для которого нужно получить идентификатор * @param bool $create Создать идентификатор, если отсутствует? * @param bool $is_new Возвращаемый прзнак, был ли создан новый идентификатор? * @return int|null */ function localId($uri, $create = true, &$is_new = false) { $is_new = false; if (!is_string($uri)) { return 0; } // Из кэша if (!isset($this->_local_ids)) { // if ($local_ids = Cache::get('mysqlstore/localids')){ // $this->_local_ids = json_decode($local_ids, true); // }else{ $this->_local_ids = array(); // } } if (isset($this->_local_ids[$uri])) { return $this->_local_ids[$uri]; } // Поиск идентифкатора URI $q = $this->db->prepare('SELECT id FROM {ids} WHERE `uri`=? LIMIT 0,1 FOR UPDATE'); $q->execute(array($uri)); if ($row = $q->fetch(DB::FETCH_ASSOC)) { $id = $row['id']; $is_new = false; $this->_local_ids[$uri] = $id; $this->_global_ids[$id] = $uri; // Отношение с родителями $q = $this->db->prepare('SELECT * FROM {parents1} WHERE `id`=? LIMIT 0,1'); $q->execute(array($id)); if ($row = $q->fetch(DB::FETCH_ASSOC)) { $this->_parents_ids[$id] = F::array_clear($row); } // Отношение с прототипами $q = $this->db->prepare('SELECT * FROM {protos1} WHERE `id`=? LIMIT 0,1'); $q->execute(array($id)); if ($row = $q->fetch(DB::FETCH_ASSOC)) { $this->_protos_ids[$id] = F::array_clear($row); } } else { if ($create) { // Создание идентификатора для URI $q = $this->db->prepare('INSERT INTO {ids} (`id`, `uri`) VALUES (null, ?)'); $q->execute([$uri]); $id = $this->db->lastInsertId('id'); $is_new = true; $obj = Data::read($uri); // Отношения с родителями $this->makeParents($id, $this->localId($obj->parent())); // Отношения с прототипами $this->makeProtos($id, $this->localId($obj->proto())); } else { return 0; } } unset($q); return intval($id); }
/** * Вспомнить пользователя * @return Entity */ protected static function remind() { self::$user = null; if (!empty(self::$input['COOKIE']['ID'])) { $ID = explode('|', self::$input['COOKIE']['ID']); } else { $ID = ''; } // Период запоминания пользователя $duration = empty($ID[0]) ? 0 : $ID[0]; // не больше месяца (примерно) // Хэш пользователя для поиска (авторизации) $hash = empty($ID[1]) ? '' : $ID[1]; // Если есть кука, то ищем пользователя в БД if ($hash) { $result = Data::find(array('from' => self::$config['users-list'], 'select' => 'children', 'depth' => 'max', 'where' => array(array('value', '=', $hash)), 'key' => false, 'limit' => array(0, 1), 'comment' => 'auth user by cookie'), false); // Пользователь найден и не истекло время его запоминания if (!empty($result)) { self::$user = $result[0]; } } else { $hash = self::get_unique_hash(); } // Новый гость if (!self::$user) { self::$user = Data::create(self::$config['user'], self::$config['users-list']); self::$user->value($hash); $duration = 0; } self::remember($duration); }