Beispiel #1
0
 public function save()
 {
     $isnew = null === $this->id;
     if (empty($this->title)) {
         $this->title = $this->name;
     }
     if (empty($this->name)) {
         throw new ValidationException('name', t('Внутреннее имя типа ' . 'не может быть пустым.'));
     } elseif (strspn(strtolower($this->name), 'abcdefghijklmnopqrstuvwxyz0123456789_') != strlen($this->name)) {
         throw new ValidationException('name', t('Внутреннее имя типа может ' . 'содержать только латинские буквы, арабские цифры и прочерк.'));
     }
     parent::checkUnique('name', t('Тип документа со внутренним именем %name уже есть.', array('%name' => $this->name)));
     // Подгружаем поля, ранее описанные отдельными объектами (9.03 => 9.05).
     $this->backportLinkedFields();
     // Добавляем привычные поля, если ничего нет.
     if ($isnew and empty($this->fields)) {
         $this->fields = array('name' => array('type' => 'TextLineControl', 'label' => t('Название'), 'required' => true, 'weight' => 10), 'uid' => array('type' => 'UserControl', 'label' => t('Автор'), 'required' => true, 'weight' => 20), 'created' => array('type' => class_exists('DateTimeControl') ? 'DateTimeControl' : 'TextLineControl', 'label' => t('Дата создания'), 'weight' => 100));
     }
     // Всегда сохраняем без очистки.
     parent::save();
     $this->publish();
     // Обновляем тип документов, если он изменился.
     if (null !== $this->oldname and $this->name != $this->oldname) {
         $this->getDB()->exec("UPDATE `node` SET `class` = ? WHERE `class` = ?", array($this->name, $this->oldname));
     }
     // Обновляем кэш.
     $this->flush();
     return $this;
 }
Beispiel #2
0
 /**
  * Сохранение группы.
  *
  * Проверяет имя группы на уникальность.
  *
  * @return Node сохранённый объект.
  */
 public function save()
 {
     if (empty($this->login)) {
         $this->login = $this->name;
     }
     parent::checkUnique('name', t('Группа с таким именем уже существует'));
     return parent::save();
 }
Beispiel #3
0
 public function save()
 {
     if ($this->isNew() and $this->parent_id) {
         $this->node = $this->parent_id;
         $this->parent_id = null;
         $this->onSave("INSERT INTO `node__rel` (`tid`, `nid`) VALUES (?, %ID%)", array($this->node));
     }
     return parent::save();
 }
Beispiel #4
0
 public function save()
 {
     if ($this->isNew()) {
         $this->onSave("INSERT INTO `node__banners` (`id`, `time_limit`, `display_limit`) VALUES (%ID%, ?, ?)", array($this->time_limit, $this->display_limit));
     } else {
         $this->onSave("UPDATE `node__banners` SET `time_limit` = ?, `display_limit` = ? WHERE `id` = %ID%", array($this->time_limit, $this->display_limit));
     }
     return parent::save();
 }
 public function add(RequestSave $request, $id = null)
 {
     if (is_null($id)) {
         if (Request::isMethod('post')) {
             $node = new Node();
             $node->name = $request->name;
             $node->ip = $request->ip;
             $node->save();
         }
     }
     return view('scripts.simulator.add');
 }
Beispiel #6
0
 public function save()
 {
     $isnew = empty($this->id);
     parent::save();
     $links = array();
     if ($this->rel) {
         $links[] = $this->rel;
     }
     if ($this->to) {
         $links[] = $this->to;
     }
     $this->linkSetParents($links);
     $this->notify($isnew);
 }
Beispiel #7
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     $input = Input::only('name', 'description');
     $rules = ['name' => 'required|max:64', 'description' => 'max:200'];
     $validator = Validator::make($input, $rules);
     if ($validator->passes()) {
         $node = new Node();
         $node->name = $input['name'];
         $node->description = $input['description'];
         $node->owner_id = Auth::user()->id;
         $node->save();
         return Redirect::back()->with('message', 'Node ' . $node->name . ' created');
     }
     return Redirect::back()->withErrors($validator);
 }
Beispiel #8
0
 public function save()
 {
     if ($isnew = !$this->id) {
         $cart = new Cart($ctx = Context::last());
         $this->orderdetails = $cart->getItems();
     } elseif (array_key_exists('orderdetails', (array) $this->olddata)) {
         $this->orderdetails = $this->olddata['orderdetails'];
     }
     if (empty($this->orderdetails)) {
         throw new ForbiddenException(t('Не удалось оформить заказ: ' . 'ваша корзина пуста. Возможно, вы его уже оформили?'));
     }
     $res = parent::save();
     if ($isnew) {
         $this->sendEmail($this->email, 'invoice');
         $this->sendEmail($ctx->config->get('modules/cart/email'), 'notification');
         $cart->setItems(array());
     }
     return $res;
 }
Beispiel #9
0
 /**
  * Сохранение раздела.
  *
  * При сохранении раздела с пустым полем parent_id, в него подставляется код
  * существующего корневого раздела (если он существует).  Привязка к типам
  * документов копируется из родительского раздела.
  *
  * @return Node ссылка на себя (для построения цепочек).
  */
 public function save()
 {
     $copyACL = false;
     if ($this->isNew()) {
         if (!$this->parent_id) {
             try {
                 Node::load(array('class' => 'tag', 'parent_id' => null, 'deleted' => 0), $this->getDB());
                 throw new RuntimeException(t('Нельзя создать новый корневой раздел.'));
             } catch (ObjectNotFoundException $e) {
             }
         }
         // Копируем родительскую привязку к типам.
         $this->onSave("INSERT INTO `node__rel` (`tid`, `nid`, `key`, `order`) " . "SELECT %ID%, `nid`, `key`, `order` FROM `node__rel` " . "WHERE `tid` = ? AND `nid` IN (SELECT `id` FROM `node` WHERE `class` = 'type')", array($this->parent_id));
         $copyACL = true;
     }
     parent::save();
     if ($copyACL) {
         ACL::copyNode($this->parent_id, $this->id);
     }
 }
Beispiel #10
0
 /**
  * Сохранение объекта.
  *
  * При сохранении картинки определяет её размеры, копирует
  * в свойства "width" и "height".  После успешного сохранения
  * (если не возникло исключение) удаляет из файлового кэша
  * отмасштабированные версии картинки (по маске attachment/id*).
  *
  * @return void
  */
 public function save()
 {
     if (!empty($this->nosave)) {
         return $this;
     }
     // К локальным файлам применяются трансформации.
     if ($this->filepath) {
         $path = os::path(MCMS_SITE_FOLDER, Context::last()->config->get('modules/files/storage'), $this->filepath);
         if ($tmp = Imgtr::transform($this)) {
             $this->versions = $tmp;
         } else {
             unset($this->versions);
         }
     }
     $res = parent::save();
     if ($this->isNew()) {
         $this->publish();
     }
     return $res;
 }
Beispiel #11
0
 public function save()
 {
     if (empty($this->id)) {
         try {
             $dst = Node::load(array('class' => 'user', 'id' => $this->re));
             if (!empty($dst->email)) {
                 $email = $dst->email;
             } elseif (false !== strstr($dst->name, '@')) {
                 $email = $dst->name;
             }
             if (!empty($email) and class_exists('BebopMimeMail')) {
                 BebopMimeMail::send(null, $email, $this->name, $this->text);
                 $this->data['sent'] = 1;
             }
             // Сохраняем в базе только если пользователь найден.
             // Чтобы можно было спокойно вызывать mcms::mail() для
             // любых объектов, не парясь с проверкой на class=user.
             return parent::save();
         } catch (ObjectNotFoundException $e) {
         }
     }
 }
Beispiel #12
0
 /**
  * create a empty node
  * @return Node
  */
 public function createEmptyNode()
 {
     $node = new Node($this);
     return $node->save();
 }
Beispiel #13
0
 /**
  * Saves model data
  *
  * @see Model::save()
  */
 public function save($data = null, $validate = true, $fieldList = array())
 {
     if (isset($data[$this->alias]['file']['tmp_name'])) {
         $data = $this->_saveUploadedFile($data);
     }
     if (!$data) {
         return $this->invalidate('file', __d('croogo', 'Error during file upload'));
     }
     return parent::save($data, $validate, $fieldList);
 }
 public function insertDefaultNodes($mindmapId)
 {
     $parent = false;
     foreach ($this->_defaultNodes as $dnode) {
         $node = new Node();
         $node->setAttributes($dnode);
         $node->mindmap_id = $mindmapId;
         if ($parent) {
             $node->parent_id = $parent;
         }
         if (!$node->save()) {
             return false;
         }
         if ($dnode['type'] == 1) {
             $parent = $node->id;
         }
     }
     return true;
 }
Beispiel #15
0
 /**
  * Сохранение профиля.
  *
  * Шифрует пароль при его изменении (MD5), проверяет имя на уникальность.
  *
  * @return Node ссылка на себя (для построения цепочек).
  */
 public function save()
 {
     parent::checkUnique('name', t('Пользователь с именем %name уже есть.', array('%name' => $this->name)));
     return parent::save();
 }
Beispiel #16
0
 public static function create_node($type, $full_path, $title, $flags = -1, $save = true)
 {
     if ($save) {
         self::lock();
     }
     self::path_parts($full_path, $path, $name);
     $node = new Node();
     $node->path = $path;
     $node->name = $name;
     $node->title = $title;
     $node->type = $type;
     $node->flags = $flags < 0 ? self::Visible | self::UserChilds : $flags;
     $node->position = self::get_max_position($path) + 1;
     if ($save) {
         $node->save();
         self::unlock();
     }
     return $node;
 }
Beispiel #17
0
 /**
  * test that saving HABTM with an empty array will clear existing HABTM if
  * unique is true
  *
  * @return void
  */
 public function testSaveHabtmEmptyData()
 {
     $this->loadFixtures('Node', 'Dependency');
     $Node = new Node();
     $data = array('Node' => array('name' => 'New First'));
     $Node->id = 1;
     $Node->save($data);
     $node = $Node->find('first', array('conditions' => array('Node.id' => 1), 'contain' => array('ParentNode')));
     $result = Hash::extract($node, 'ParentNode.{n}.id');
     $expected = array(2);
     $this->assertEquals($expected, $result);
     $data = array('ParentNode' => array());
     $Node->id = 1;
     $Node->save($data);
     $node = $Node->find('first', array('conditions' => array('Node.id' => 1), 'contain' => array('ParentNode')));
     $result = Hash::extract($node, 'ParentNode.{n}.id');
     $expected = array();
     $this->assertEquals($expected, $result);
 }
 /**
  * Creates a node based on default settings.
  *
  * @param $settings
  *   An associative array of settings to change from the defaults, keys are
  *   node properties, for example 'title' => 'Hello, world!'.
  * @return Node
  *   Created node entity.
  */
 protected function backdropCreateNode($settings = array())
 {
     // Populate defaults array.
     $settings += array('body' => array(LANGUAGE_NONE => array(array())), 'title' => $this->randomName(8), 'comment' => 2, 'changed' => REQUEST_TIME, 'moderate' => 0, 'promote' => 0, 'revision' => 1, 'log' => '', 'status' => 1, 'sticky' => 0, 'type' => 'page', 'revisions' => NULL, 'langcode' => LANGUAGE_NONE);
     // Use the original node's created time for existing nodes.
     if (isset($settings['created']) && !isset($settings['date'])) {
         $settings['date'] = format_date($settings['created'], 'custom', 'Y-m-d H:i:s O');
     }
     // If the node's user uid is not specified manually, use the currently
     // logged in user if available, or else the user running the test.
     if (!isset($settings['uid'])) {
         if ($this->loggedInUser) {
             $settings['uid'] = $this->loggedInUser->uid;
         } else {
             global $user;
             $settings['uid'] = $user->uid;
         }
     }
     // Merge body field value and format separately.
     $body = array('value' => $this->randomName(32), 'format' => filter_default_format());
     $settings['body'][$settings['langcode']][0] += $body;
     $node = new Node($settings);
     $node->save();
     // Small hack to link revisions to our test user.
     db_update('node_revision')->fields(array('uid' => $node->uid))->condition('vid', $node->vid)->execute();
     return $node;
 }