public static function rpc_get_confirm(Context $ctx)
 {
     if (!is_array($data = unserialize(base64_decode($ctx->get('code'))))) {
         throw new BadRequestException();
     }
     // Немного валидации, на т.к. будем в БД класть данные.
     foreach ($data['sections'] as $k => $v) {
         if (!is_numeric($v)) {
             throw new BadRequestException();
         }
     }
     // Номер последней ноды нужен для того, чтобы не отправлять
     // новому подписчику уже существующие новости.
     $last = $ctx->db->getResult("SELECT MAX(`id`) FROM `node`");
     try {
         $node = Node::load(array('class' => 'subscription', 'name' => $data['email'], 'deleted' => 0));
         $status = t('Параметры подписки успешно изменены.');
     } catch (ObjectNotFoundException $e) {
         $node = Node::create(array('class' => 'subscription', 'name' => $data['email'], 'last' => $last, 'published' => true));
         $status = t('Подписка активирована.');
     }
     $ctx->db->beginTransaction();
     if (!empty($data['sections'])) {
         $node->tags = $data['sections'];
         $node->linkTo($data['sections'])->save();
     } elseif (!empty($node->id)) {
         $node->delete();
         $status = t('Подписка удалена.');
     }
     $ctx->db->commit();
     return $ctx->getRedirect('?status=subscribed');
 }
 public static function checkTypes()
 {
     if (!Node::count(array('class' => 'type', 'name' => 'comment'))) {
         $type = Node::create('type', array('name' => 'comment', 'title' => t('Комментарий'), 'fields' => array('name' => array('type' => 'TextLineControl', 'label' => t('Ваше имя'), 'required' => true), 'body' => array('type' => 'TextAreaControl', 'label' => t('Сообщение')), 'email' => array('type' => 'EmailControl', 'label' => t('E-mail'), 'required' => true), 'url' => array('type' => 'URLControl', 'label' => t('Домашняя страница')), 'ip' => array('type' => 'TextLineControl', 'label' => t('IP адрес'), 'hidden' => true))));
         $type->save();
     }
 }
Exemple #3
0
 private function installTypes()
 {
     if (!Node::count($this->ctx->db, array('class' => 'type', 'name' => 'blog'))) {
         $type = Node::create('type', array('name' => 'blog', 'title' => t('Запись в дневнике'), 'description' => t('Ваш дневник — ваше личное пространство на этом сервере.  Можете писать здесь всё, что угодно. Другие пользователи смогут это читать и комментировать, но на главную страницу эта информация не попадёт.  Туда попадают только статьи.'), 'fields' => array('name' => array('type' => 'TextLineControl', 'label' => t('Заголовок'), 'required' => true), 'teaser' => array('type' => 'TextAreaControl', 'label' => t('Краткое содержание')), 'body' => array('type' => 'TextHTMLControl', 'label' => t('Текст записи'), 'required' => true), 'picture' => array('type' => 'AttachmentControl', 'label' => t('Иллюстрация')))));
         $type->save();
     }
 }
 public function set($value, &$node)
 {
     if (empty($value) or !is_array($value)) {
         return;
     }
     switch ($value['error']) {
         case UPLOAD_ERR_OK:
             $value = Node::create('file')->import($value);
             break;
         case UPLOAD_ERR_INI_SIZE:
             throw new RuntimeException(t('Размер файла превышает установленное в системе ограничение (%size).', array('%size' => ini_get('upload_max_filesize'))));
         case UPLOAD_ERR_FORM_SIZE:
             throw new RuntimeException(t('Размер файла превышает установленное в форме ограничение.'));
         case UPLOAD_ERR_PARTIAL:
             throw new RuntimeException(t('Файл получен не полностью.'));
         case UPLOAD_ERR_NO_FILE:
             if (!empty($value['id']) and is_numeric($value['id'])) {
                 $value = Node::load($value['id']);
             } elseif (!empty($value['url'])) {
                 $value = FileNode::fromURL($value['url']);
             } elseif (!empty($value['ftp'])) {
                 $value = Node::create('file')->importFromFTP(array_shift($value['ftp']));
             } elseif (!empty($value['unlink'])) {
                 $node->linkRemoveChild(null, $this->value);
                 $value = null;
             } else {
                 $value = $node->{$this->value};
             }
     }
     if ($this->required and empty($value)) {
         throw new ValidationException($this->label, t('Вы не загрузили файл в поле «%name», хотя оно отмечено как обязательное.', array('%name' => mb_strtolower($this->label))));
     }
     $node->{$this->value} = $value;
 }
 private function installTypes()
 {
     // ЧАСТЬ ПЕРВАЯ: заказ.
     if (!Node::count(array('class' => 'type', 'name' => 'order'))) {
         $type = Node::create('type', array('name' => 'order', 'title' => t('Заказ'), 'description' => t('Документы этого типа создаются автоматически при оформлении заказов на сайте.'), 'fields' => array('name' => array('type' => 'TextLineControl', 'label' => t('Ф.И.О.'), 'description' => t('Эта информация нужна нам для обратной связи и доставки (если она осуществляется).'), 'required' => true), 'email' => array('type' => 'EmailControl', 'label' => t('Адрес электронной почты'), 'required' => true), 'phone' => array('type' => 'TextLineControl', 'label' => t('Контактный телефон')), 'address' => array('type' => 'TextAreaControl', 'label' => t('Адрес доставки')), 'orderdetauks' => array('type' => 'OrderDetailsControl', 'label' => t('Содержимое заказа'), 'required' => false, 'readonly' => true))));
         $type->save();
     }
 }
 /**
  * @mcms_message ru.molinos.cms.install
  */
 public static function onInstall(Context $ctx)
 {
     $count = Node::count(array('class' => 'type', 'name' => 'order', 'deleted' => 0), $ctx->db);
     if (!$count) {
         $ctx->db->beginTransaction();
         Node::create(array('class' => 'type', 'name' => 'order', 'title' => 'Заказ'))->save();
         $ctx->db->commit();
     }
 }
Exemple #7
0
 public function store()
 {
     $validator = Validator::make($data = Input::all(), Node::$rules);
     if ($validator->fails()) {
         return Redirect::back()->withErrors($validator)->withInput();
     }
     Node::create($data);
     return Redirect::route('nodes.index');
 }
 public function onGet(array $options)
 {
     $sections = array_intersect_key(Node::getSortedList('tag'), array_flip(Node::create('subscription')->getEnabledSections()));
     $output = html::simpleOptions($sections, 'section', 'sections');
     if ($this->description) {
         $output .= html::em('description', html::cdata($this->description));
     }
     return $output;
 }
 /**
  * Добавляет тип документа label.
  *
  * @mcms_message ru.molinos.cms.install
  */
 public static function onInstall(Context $ctx)
 {
     try {
         $node = Node::load(array('class' => 'type', 'name' => 'label'), $ctx->db);
     } catch (ObjectNotFoundException $e) {
         $ctx->db->beginTransaction();
         $node = Node::create(array('class' => 'type', 'name' => 'label', 'label' => t('Метка'), 'isdictionary' => true, 'fields' => array('name' => array('type' => 'TextLineControl', 'title' => t('Метка'), 'required' => true))), $ctx->db)->save();
         $ctx->db->commit();
     }
 }
Exemple #10
0
 /**
  * Register a node type.
  *
  * @param string $type
  * @param array  $route
  */
 public function registerType($type, array $route)
 {
     if (isset($route['protected']) and $route['protected'] and !array_filter(Node::findAll(true), function ($node) use($type) {
         return $type === $node->type;
     })) {
         Node::create(['title' => $route['label'], 'slug' => App::filter($route['label'], 'slugify'), 'type' => $type, 'status' => 1, 'link' => $route['name']])->save();
     }
     $route['id'] = $type;
     $this->types[$type] = $route;
 }
 /**
  * Инсталляция типа документа subscription.
  *
  * @mcms_message ru.molinos.cms.install
  */
 public static function onInstall(Context $ctx)
 {
     try {
         $node = Node::load(array('class' => 'type', 'name' => 'subscription', 'deleted' => 0), $ctx->db);
     } catch (ObjectNotFoundException $e) {
         $ctx->db->beginTransaction();
         $node = Node::create('type', array('name' => 'subscription', 'title' => t('Подписка на новости')))->save();
         $ctx->db->commit();
     }
 }
 public static function rpc_post_add(Context $ctx)
 {
     $ctx->user->checkAccess(ACL::CREATE, 'comment');
     $node = Node::create('comment', array('published' => $ctx->user->hasAccess(ACL::PUBLISH, 'comment')));
     $node->formProcess($ctx->post);
     if ($ctx->post('anonymous')) {
         $node->name = t('Комментарий анонимный');
         $node->uid = null;
     }
     $node->save();
 }
 /**
  * @mcms_message ru.molinos.cms.install
  */
 public static function on_install(Context $ctx)
 {
     try {
         $node = Node::load(array('class' => 'type', 'name' => 'tag', 'deleted' => 0), $ctx->db);
     } catch (ObjectNotFoundException $e) {
         $node = Node::create(array('class' => 'type', 'name' => 'tag', 'title' => t('Раздел'), 'fields' => array('name' => array('type' => 'TextLineControl', 'title' => t('Имя раздела'), 'required' => true))), $ctx->db);
         $node->getDB()->beginTransaction();
         $node->save();
         $node->getDB()->commit();
     }
 }
 public function create(Model $Model, $fields = null, $values = null)
 {
     $data = array($this->Node->alias => array_combine($fields, $values));
     $data[$this->Node->alias]['type'] = Inflector::singularize($Model->table);
     if (!$this->Node->create()) {
         return false;
     }
     $data = $this->__moveCustomToCustomFields($Model, $data);
     $result = $this->Node->saveAll($data, array('deep' => true));
     return $result;
 }
 public function set($value, &$node)
 {
     $this->validate($value);
     if (null === ($email = $this->findEmail($node))) {
         throw new InvalidArgumentException(t('Не удалось подписать вас на новости: в профиле не обнаружен ни один почтовый адрес.'));
     }
     $s = Node::find(array('class' => 'subscription', 'name' => $email), $node->getDB());
     if (empty($s)) {
         $s = Node::create('subscription', array('name' => $email));
     } else {
         $s = array_shift($s);
     }
     $s->linkSetParents($value, 'tag', $this->enabled)->save();
 }
 protected function getData()
 {
     $data = Node::find(array('class' => 'type', 'deleted' => 0, '#sort' => '-published name'), $this->ctx->db);
     $counts = $this->ctx->db->getResultsKV("name", "count", "SELECT `class` AS `name`, COUNT(*) AS `count` FROM `node` WHERE `deleted` = 0 GROUP BY `class`");
     $nodes = '';
     foreach ($data as $node) {
         if ($node->isdictionary) {
             $attrs = array('id' => $node->id, 'name' => $node->name, 'title' => $node->title, 'list' => Node::create($node->name)->getListURL(), 'published' => (bool) $node->published);
             $attrs['count'] = array_key_exists($node->name, $counts) ? $counts[$node->name] : 0;
             $nodes .= html::em('node', $attrs);
         }
     }
     return html::wrap('data', $nodes);
 }
 /**
  * Добавление нового пользователя.
  * 
  * @param Context $ctx 
  * @param array $params 
  * @return void
  * @mcms_message ru.molinos.cms.auth.process.basicreg
  */
 public static function on_register(Context $ctx, array $params)
 {
     if (empty($params['password1'])) {
         throw new BadRequestException(t('Пароль не может быть пустым.'));
     }
     if ($params['password1'] != ($password = $params['password2'])) {
         throw new BadRequestException(t('Пароль подтверждён неверно.'));
     }
     $ctx->db->beginTransaction();
     $node = Node::create(array('class' => 'user', 'name' => $params['email'], 'published' => 1));
     $node->setPassword($password);
     $node->save();
     $ctx->db->commit();
     $ctx->user->login($node->name, $password);
 }
 public static function on_get_create_form(Context $ctx)
 {
     $node = Node::create('type', array('parent_id' => $parent_id, 'isdictionary' => true));
     $schema = $node->getFormFields();
     unset($schema['tags']);
     // unset($schema['fields']);
     $schema['isdictionary'] = new HiddenControl(array('value' => 'isdictionary', 'default' => 1));
     $form = $schema->getForm();
     $form->title = t('Добавление справочника');
     $form->addClass('tabbed');
     $form->action = "?q=nodeapi.rpc&action=create&type=type&destination=admin/content/dict";
     $form->addControl(new SubmitControl(array('text' => t('Добавить'))));
     $page = new AdminPage(html::em('content', array('name' => 'create'), $form->getXML($node)));
     return $page->getResponse($ctx);
 }
Exemple #19
0
 public function create()
 {
     if (!isset($this->node_parent)) {
         $this->node_parent = 0;
     }
     if (!isset($this->node_root)) {
         $this->node_root = 0;
     }
     $N = new Node();
     $N->id_parent = $this->node_parent;
     $N->id_root = $this->node_root;
     $N->table_alias = self::ALIAS;
     $N->create();
     $this->variables[$this->pk] = $N->db()->lastInsertId();
     return parent::create();
 }
 public static function openIDAuthorize($openid_mode, Context $ctx)
 {
     self::includeOpenID();
     $mode = $ctx->config->get('modules/openid/mode', 'open');
     if ('none' == $mode) {
         throw new RuntimeException(t('Поддержка OpenID отключена администратором.'));
     }
     if ('id_res' == $openid_mode) {
         $openid = null;
         foreach (array('openid1_claimed_id', 'openid_claimed_id', 'openid_identity') as $key) {
             if (!empty($_GET[$key])) {
                 $openid = $_GET[$key];
                 break;
             }
         }
         if (null === $openid) {
             throw new RuntimeException('OpenID провайдер не вернул идентификатор.');
         }
         $nodes = Node::find(array('class' => 'user', 'name' => $openid, 'deleted' => 0), $ctx->db);
         if (!count($nodes)) {
             if ('open' != $mode) {
                 throw new ForbiddenException(t('Извините, автоматическая регистрация пользователей через OpenID отключена.'));
             }
             $fieldmap = array('sreg_email' => 'email', 'sreg_fullname' => 'fullname', 'sreg_nickname' => 'nickname');
             $node = Node::create(array('class' => 'user', 'parent_id' => null, 'name' => $openid, 'published' => true));
             foreach ($fieldmap as $k => $v) {
                 if (!empty($_GET[$key = 'openid_' . $k])) {
                     $node->{$v} = $_GET[$key];
                 }
             }
             $node->setRegistered($ctx);
             $node->save();
         } else {
             $node = array_shift($nodes);
             if (!$node->published) {
                 throw new ForbiddenException(t('Ваш профиль заблокирован.'));
             }
         }
         return $node;
     } else {
         // Login canceled
         Logger::log('login cancelled ?!');
         $ctx->redirect("auth/logout.rpc");
     }
 }
 /**
  * Поиск (обработка).
  */
 public static function on_post_search_form(Context $ctx)
 {
     $list = 'admin/content/list';
     $term = $ctx->post('search_term');
     if (null !== ($tmp = $ctx->post('search_class'))) {
         $list = Node::create($tmp)->getListURL();
     }
     $url = new url($ctx->get('from', $list));
     if (null !== ($tmp = $ctx->post('search_uid'))) {
         $url->setarg('author', $tmp);
     }
     if (null !== ($tmp = $ctx->post('search_tag'))) {
         $term .= ' tags:' . $tmp;
     }
     $url->setarg('search', trim($term));
     $url->setarg('page', null);
     $ctx->redirect($url->string());
 }
Exemple #22
0
 public static function hookRemoteCall(Context $ctx)
 {
     switch ($ctx->get('action')) {
         case 'add':
             $ctx->user->checkAccess(ACL::CREATE, 'todo');
             $node = Node::create('todo', array('name' => $ctx->post('name'), 'uid' => $ctx->user->id, 'to' => $ctx->post('user', $ctx->user->id), 'published' => 1, 'rel' => $ctx->post('rel')));
             if (empty($node->name)) {
                 $msg = t('не указан текст задачи.');
                 bebop_on_json(array('status' => 'error', 'message' => $msg));
                 throw new InvalidArgumentException($msg);
             }
             $node->save();
             bebop_on_json(array('status' => 'created', 'id' => $node->id, 'html' => $node->render()));
             break;
         case 'toggle':
             try {
                 $node = Node::load(array('class' => 'todo', 'id' => $ctx->get('id')));
             } catch (ObjectNotFoundException $e) {
                 bebop_on_json(array('status' => 'error', 'message' => 'todo ' . $ctx->get('id') . ' not found'));
                 throw new PageNotFoundException();
             }
             if (empty($node->closed)) {
                 $node->closed = date('Y-m-d H:i:s', time() - date('Z', time()));
             } else {
                 $node->closed = null;
             }
             $node->save();
             if ($ctx->method('POST') and null !== ($comment = $ctx->post('comment'))) {
                 $tmp = Node::create('comment', array('uid' => $ctx->user->id, 'author' => $ctx->user->name, 'name' => t('Комментарий к напоминанию'), 'text' => $comment));
                 $tmp->save();
                 $tmp->linkAddParent($node->id);
             }
             $state = $node->closed ? 'closed' : 'open';
             bebop_on_json(array('status' => 'ok', 'state' => $state));
             break;
     }
 }
 public function set($value, &$node)
 {
     $this->validate($value);
     $fieldName = $this->value . '*';
     $node->onSave("DELETE FROM `node__rel` WHERE `nid` = %ID% AND `key` = ?", array($fieldName));
     if (empty($value)) {
         unset($node->{$this->value});
     } else {
         $result = array();
         $labels = preg_split('/,\\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
         foreach ($labels as $label) {
             try {
                 $label = trim($label);
                 $tmp = Node::load($f = array('class' => 'label', 'name' => $label, 'deleted' => 0), $node->getDB());
             } catch (ObjectNotFoundException $e) {
                 $tmp = Node::create(array('class' => 'label', 'name' => $label, 'published' => 1), $node->getDB())->save();
             }
             $result[$tmp->id] = $tmp->name;
         }
         $params = array($fieldName);
         $node->onSave($sql = "INSERT INTO `node__rel` (`nid`, `tid`, `key`) SELECT %ID%, `id`, ? FROM `node` WHERE `class` = 'label' AND `id` " . sql::in(array_keys($result), $params), $params);
         $node->{$this->value} = $result;
     }
 }
Exemple #24
0
 /**
  * Возвращает форму для создания документа.
  */
 public static function on_get_create_form(Context $ctx)
 {
     if (!($type = $ctx->get('type'))) {
         throw new BadRequestException(t('Не указан тип документа (GET-параметр type).'));
     }
     $node = Node::create(array('class' => $type, 'parent_id' => $ctx->get('parent')))->knock(ACL::CREATE);
     $form = $node->formGet();
     // destination берётся из $_SERVER, и при работе через XML API содержит не то,
     // что может быть нужно, поэтому корректируем руками.
     $action = new url($form->action);
     $action->setarg('destination', $ctx->get('destination'));
     $form->action = $action->string();
     $form->addClass('create');
     $form->addClass('create-' . $type);
     return new Response($form->getXML(Control::data()), 'text/xml');
 }
Exemple #25
0
 private function checkPermission()
 {
     return Node::create('order')->checkPermission(ACL::CREATE);
 }
 /**
  * Создание объекта.
  */
 public static function rpc_post_create(Context $ctx)
 {
     $parent = $ctx->post('parent_id');
     $node = Node::create(array('class' => $ctx->get('type'), 'parent_id' => empty($parent) ? null : $parent), $ctx->db)->knock(ACL::CREATE);
     $node->formProcess($ctx->post)->save($ctx->db);
     $next = $ctx->post('destination', $ctx->get('destination', ''));
     return new Redirect(self::fixredir($next, $node));
 }
Exemple #27
0
 protected function createNode()
 {
     $node = new Node();
     $node->create();
 }
Exemple #28
0
 public function getPreviewXML(Context $ctx)
 {
     $result = parent::getPreviewXML($ctx);
     if (!$this->published) {
         $message = t('Документы этого (скрытого) типа не отображаются в обычном <a href="@url1">списке документов</a>, их не предлагают в стандартной <a href="@url2">форме создания документа</a>.', array('@url1' => 'admin/content/list', '@url2' => 'admin/create'));
         $result .= html::em('field', array('title' => t('Комментарий')), html::em('value', html::cdata($message)));
     }
     $count = Node::count(array('class' => $this->name, 'deleted' => 0), $ctx->db);
     if ($count) {
         $message = t('%count документов (<a href="@url">список</a>)', array('%count' => $count, '@url' => Node::create($this->name)->getListURL()));
         $result .= html::em('field', array('title' => t('Статистика')), html::em('value', html::cdata($message)));
     }
     return $result;
 }
 public static function on_get_create_form(Context $ctx, $path, array $pathinfo, $type, $parent_id = null)
 {
     $node = Node::create(array('class' => $type, 'parent_id' => $parent_id, 'isdictionary' => $ctx->get('dictionary')));
     if ($nodeargs = $ctx->get('node')) {
         foreach ($nodeargs as $k => $v) {
             $node->{$k} = $v;
         }
     }
     $form = $node->formGet();
     $form->addClass('tabbed');
     $form->addClass("node-{$type}-create-form");
     $form->action = "?q=nodeapi.rpc&action=create&type={$type}&destination=" . urlencode($ctx->get('destination'));
     if ($node->parent_id) {
         $form->addControl(new HiddenControl(array('value' => 'parent_id', 'default' => $node->parent_id)));
     }
     if ($ctx->get('dictionary')) {
         if (null !== ($tmp = $form->findControl('tab_general'))) {
             $tmp->intro = t('Вы создаёте первый справочник.  Вы сможете использовать его значения в качестве выпадающих списков (для этого надо будет добавить соответствующее поле в нужный <a href=\'@types\'>тип документа</a>).', array('@types' => '?q=admin&cgroup=structure&mode=list&preset=schema'));
         }
         $form->hideControl('tab_sections');
         if (null !== ($ctl = $form->findControl('title'))) {
             $ctl->label = t('Название справочника');
         }
         if (null !== ($ctl = $form->findControl('name'))) {
             $ctl->label = t('Внутреннее имя справочника');
         }
         $form->addControl(new HiddenControl(array('value' => 'isdictionary', 'default' => 1)));
     }
     $page = new AdminPage(html::em('content', array('name' => 'create'), $form->getXML($node)));
     return $page->getResponse($ctx);
 }
Exemple #30
0
 /**
  * Загрузка нод из БД.
  *
  * Параметры:
  *   $query — запрос.
  *   $db — БД. Если не указана, используется текущее подключение.
  */
 public static function find($query, Database $db = null)
 {
     if (is_array($query)) {
         $query = Query::build($query);
     } elseif (!$query instanceof Query) {
         throw new InvalidArgumentException(t('Запрос должен быть массивом или объектом Query.'));
     }
     if (null === $db) {
         $db = Context::last()->db;
     }
     list($sql, $params) = $query->getSelect();
     $sth = $db->prepare($sql);
     $sth->execute($params);
     $result = array();
     while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
         $result[$row['id']] = Node::create($row, $db);
     }
     return $result;
 }