/** * Save data. * * @param array $data Data. * @return bool|mixed * * @throws SystemException 'ERR_VALIDATE_FORM' */ protected function saveData($data) { $result = false; //создаем объект описания данных $dataDescriptionObject = new DataDescription(); //получаем описание полей для метода $configDataDescription = $this->getConfig()->getStateConfig($this->getPreviousState()); //если в конфиге есть описание полей для метода - загружаем их if (isset($configDataDescription->fields)) { $dataDescriptionObject->loadXML($configDataDescription->fields); } //Создаем объект описания данных взятых из БД $DBDataDescription = new DataDescription(); //Загружаем в него инфу о колонках $DBDataDescription->load($this->loadDataDescription()); $this->setDataDescription($dataDescriptionObject->intersect($DBDataDescription)); $dataObject = new Data(); $dataObject->load($data); $this->setData($dataObject); //Создаем сейвер $saver = new Saver(); //Устанавливаем его режим $saver->setMode(self::COMPONENT_TYPE_FORM_ADD); $saver->setDataDescription($this->getDataDescription()); $saver->setData($this->getData()); if ($saver->validate() === true) { $saver->setFilter($this->getFilter()); $saver->save(); $result = $saver->getResult(); } else { //выдвигается пустой exception который перехватывается в методе save throw new SystemException('ERR_VALIDATE_FORM', SystemException::ERR_WARNING, $saver->getErrors()); } return $result; }
protected function main() { $id = !($id = $this->getParam('id')) ? $this->document->getID() : $id; $this->setBuilder(new SimpleBuilder()); $dd = new DataDescription(); if ($this->getConfig()->getCurrentStateConfig() && $this->getConfig()->getCurrentStateConfig()->fields) { $dd->loadXML($this->getConfig()->getCurrentStateConfig()->fields); } else { $dd->load(['Id' => ['type' => FieldDescription::FIELD_TYPE_INT], 'Name' => ['type' => FieldDescription::FIELD_TYPE_STRING], 'Title' => ['type' => FieldDescription::FIELD_TYPE_STRING], 'HtmlTitle' => ['type' => FieldDescription::FIELD_TYPE_STRING], 'DescriptionRtf' => ['type' => FieldDescription::FIELD_TYPE_HTML_BLOCK]]); } $fd = new FieldDescription('Url'); $fd->setType(FieldDescription::FIELD_TYPE_STRING); $dd->addFieldDescription($fd); $info = E()->getMap()->getDocumentInfo($id); $d = new Data(); $info['Id'] = $id; $info['Url'] = E()->getMap()->getURLByID($id); $d->load([$info]); $this->setDataDescription($dd); $this->setData($d); $m = new AttachmentManager($this->getDataDescription(), $this->getData(), 'share_sitemap', true); $m->createFieldDescription(); $m->createField('smap_id', false, $id); $this->addToolbar($this->loadToolbar()); $this->js = $this->buildJS(); }
/** * Get data. * * @param string|int $langID Language ID. * @param mixed $filter filter. * @return Data */ public function getData($langID, $filter = null) { $result = new Data(); if (empty($filter)) { $dataArray = array(); $i = 0; foreach ($this->dbh->getColumnsInfo($this->tableName) as $rowName => $rowValue) { array_push($dataArray, array('field_id' => ++$i, 'lang_id' => $langID, 'field_type' => FieldDescription::convertType($rowValue['type'], $rowName, $rowValue['length'], $rowValue), 'field_type_real' => FieldDescription::convertType($rowValue['type'], $rowName, $rowValue['length'], $rowValue), 'field_name' => $this->translate($this->getFieldLTag($rowName), $langID), 'field_is_nullable' => $rowValue['nullable'])); } $result->load($dataArray); } return $result; }
private function buildGroups(Field $field) { $builder = new SimpleBuilder(); $data = new Data(); $dd = new DataDescription(); $dd->load(['id' => ['type' => FieldDescription::FIELD_TYPE_INT, 'key' => true], 'link' => ['type' => FieldDescription::FIELD_TYPE_STRING], 'title' => ['type' => FieldDescription::FIELD_TYPE_STRING], 'text' => ['type' => FieldDescription::FIELD_TYPE_HTML_BLOCK]]); $builder->setDataDescription($dd); foreach ($field as $key => $id) { if ($d = $this->dbh->select('SELECT t.top_id as id, top_name as `title`, top_link as link,top_text_rtf as `text` FROM apps_tops t LEFT JOIN apps_tops_translation tt ON (tt.top_id=t.top_id) AND (lang_id=%s) WHERE (t.tg_id =%s) AND top_is_active ORDER BY top_order_num', $this->document->getLang(), $id)) { $data->load($d); $builder->setData($data); $am = new AttachmentManager($dd, $data, 'apps_tops'); $am->createFieldDescription(); $am->createField('top_id', false, $data->getFieldByName('id')->getData()); $builder->build(); $field->setRowData($key, $builder->getResult()); } else { $field->setRowData($key, null); } } }
protected function saveData() { $result = false; //если в POST не пустое значение значение первичного ключа - значит мы находимся в режиме редактирования if (isset($_POST[$this->getTableName()][$this->getPK()]) && !empty($_POST[$this->getTableName()][$this->getPK()])) { $mode = self::COMPONENT_TYPE_FORM_ALTER; $this->setFilter([$this->getPK() => $_POST[$this->getTableName()][$this->getPK()]]); } else { $mode = self::COMPONENT_TYPE_FORM_ADD; } //создаем объект описания данных $dataDescriptionObject = new DataDescription(); if (!method_exists($this, $this->getPreviousState())) { throw new SystemException('ERR_NO_ACTION', SystemException::ERR_CRITICAL); } //получаем описание полей для метода $configDataDescription = $this->getConfig()->getStateConfig($this->getPreviousState()); //если в конфиге есть описание полей для метода - загружаем их if (isset($configDataDescription->fields)) { $dataDescriptionObject->loadXML($configDataDescription->fields); } //Создаем объект описания данных взятых из БД $DBDataDescription = new DataDescription(); //Загружаем в него инфу о колонках $DBDataDescription->load($this->loadDataDescription()); $this->setDataDescription($dataDescriptionObject->intersect($DBDataDescription)); //Поле с порядком следования убираем из списка if (($col = $this->getOrderColumn()) && ($field = $this->getDataDescription()->getFieldDescriptionByName($col))) { $this->getDataDescription()->removeFieldDescription($field); } $dataObject = new Data(); $dataObject->load($this->loadData()); $this->setData($dataObject); //Создаем сейвер $saver = $this->getSaver(); //Устанавливаем его режим $saver->setMode($mode); $saver->setDataDescription($this->getDataDescription()); $saver->setData($this->getData()); if ($saver->validate() === true) { $saver->setFilter($this->getFilter()); $saver->save(); $result = $saver->getResult(); } else { //выдвигается exception который перехватывается в методе save throw new SystemException('ERR_VALIDATE_FORM', SystemException::ERR_WARNING, $this->saver->getErrors()); } //Если у нас режим вставки и определена колонка для порядка следования, // изменяем порядок следования if (($orderColumn = $this->getOrderColumn()) && $mode == self::COMPONENT_TYPE_FORM_ADD) { $linkedID = $this->getParam('linkedID'); $pk = $this->getParam('pk'); if ($linkedID) { $new_order_num = $this->dbh->getScalar('SELECT max(' . $orderColumn . ') as max_order_num FROM ' . $this->getTableName() . ' WHERE `' . $pk . '` = %s', $linkedID); } else { $new_order_num = $this->dbh->getScalar('SELECT max(' . $orderColumn . ') as max_order_num FROM ' . $this->getTableName() . ' WHERE `' . $pk . '` IS NULL AND session_id = %s ', session_id()); } $new_order_num = !$new_order_num ? 1 : $new_order_num + 1; $this->addFilterCondition([$this->getPK() . '=' . $result]); $request = 'UPDATE ' . $this->getTableName() . ' SET ' . $orderColumn . ' = %s ' . $this->dbh->buildWhereCondition($this->getFilter()); $this->dbh->modify($request, $new_order_num); } return $result; }
/** * Build comments. * * @param array $data Data. * @return \DOMNode */ private function buildComments($data) { $localData = new Data(); if (is_array($data)) { $localData->load($data); } $dataDescription = $this->createNewDataDescription(); $builder = $this->isTree && !$localData->isEmpty() ? new TreeBuilder() : new Builder(); $builder->setData($localData); $builder->setDataDescription($dataDescription); if ($this->isTree && !$localData->isEmpty()) { $tree = TreeConverter::convert($data, 'comment_id', 'comment_parent_id'); $builder->setTree($tree); } $builder->build(); return $builder->getResult(); }
/** * Replace data. * @param array $data Data in the form @code array(array('Id'=>'', 'Name'=>'', 'Segment'=>'')) @endcode */ public function replaceData($data) { $d = new Data(); $d->load($data); $this->setData($d); }
/** * Build tab with division rights. * * @return DOMNode */ private function buildDivRightsData() { $builder = new TreeBuilder(); $builder->setTree(TreeConverter::convert($this->dbh->select('share_sitemap', ['smap_id', 'smap_pid'], null, ['smap_order_num' => QAL::ASC]), 'smap_id', 'smap_pid')); $id = $this->getFilter(); $id = !empty($id) ? current($id) : ''; $data = convertDBResult($this->dbh->select('select s.smap_id as Id, smap_pid as Pid, site_id as Site, smap_name as Name ' . 'from share_sitemap s ' . 'left join share_sitemap_translation st on st.smap_id = s.smap_id ' . 'where lang_id=%s', E()->getLanguage()->getCurrent()), 'Id'); foreach ($data as $smapID => $smapInfo) { $data[$smapID]['RightsId'] = E()->getMap($smapInfo['Site'])->getDocumentRights($smapID, $id); $data[$smapID]['Site'] = E()->getSiteManager()->getSiteByID($smapInfo['Site'])->name; } $dataObject = new Data(); $dataObject->load($data); $builder->setData($dataObject); $dataDescriptionObject = new DataDescription(); $f = new FieldDescription('Id'); $f->setType(FieldDescription::FIELD_TYPE_INT); $f->setProperty('key', true); $dataDescriptionObject->addFieldDescription($f); $f = new FieldDescription('Pid'); $f->setType(FieldDescription::FIELD_TYPE_INT); $dataDescriptionObject->addFieldDescription($f); $f = new FieldDescription('Name'); $f->setType(FieldDescription::FIELD_TYPE_STRING); $dataDescriptionObject->addFieldDescription($f); $f = new FieldDescription('Site'); $f->setType(FieldDescription::FIELD_TYPE_STRING); $dataDescriptionObject->addFieldDescription($f); $f = new FieldDescription('RightsId'); $f->setType(FieldDescription::FIELD_TYPE_SELECT); if ($this->getState() == 'view') { $f->setMode(FieldDescription::FIELD_MODE_READ); } $rights = $this->dbh->select('user_group_rights', ['right_id', 'right_const']); $rights = array_merge([['right_id' => 0, 'right_const' => 'NO_RIGHTS']], $rights); foreach ($rights as $key => $value) { $rights[$key]['right_const'] = $this->translate('TXT_' . $value['right_const']); } $f->loadAvailableValues($rights, 'right_id', 'right_const'); $dataDescriptionObject->addFieldDescription($f); $builder->setData($dataObject); $builder->setDataDescription($dataDescriptionObject); $builder->build(); return $builder->getResult(); }
/** * Save data. * @return mixed * @throws SystemException 'ERR_NO_ACTION' * @throws SystemException 'ERR_VALIDATE_FORM' */ protected function saveData() { $result = false; //если в POST не пустое значение значение первичного ключа - значит мы находимся в режиме редактирования if (isset($_POST[$this->getTableName()][$this->getPK()]) && !empty($_POST[$this->getTableName()][$this->getPK()])) { $mode = self::COMPONENT_TYPE_FORM_ALTER; $this->setFilter([$this->getPK() => $_POST[$this->getTableName()][$this->getPK()]]); } else { $mode = self::COMPONENT_TYPE_FORM_ADD; } //создаем объект описания данных $dataDescriptionObject = new DataDescription(); if (!method_exists($this, $this->getPreviousState())) { throw new SystemException('ERR_NO_ACTION', SystemException::ERR_CRITICAL); } //получаем описание полей для метода $configDataDescription = $this->getConfig()->getStateConfig($this->getPreviousState()); //если в конфиге есть описание полей для метода - загружаем их if (isset($configDataDescription->fields)) { $dataDescriptionObject->loadXML($configDataDescription->fields); } //Создаем объект описания данных взятых из БД $DBDataDescription = new DataDescription(); //Загружаем в него инфу о колонках $DBDataDescription->load($this->loadDataDescription()); $this->setDataDescription($dataDescriptionObject->intersect($DBDataDescription)); //Поле с порядком следования убираем из списка /** * @todo Надо бы это как то переделать, потому что разбросано получилось * часть кода относящаяся к обработке колонки с нумерацией здесь, часть * @see Grid::createDataDescription */ if (($col = $this->getOrderColumn()) && ($field = $this->getDataDescription()->getFieldDescriptionByName($col))) { $this->getDataDescription()->removeFieldDescription($field); } $dataObject = new Data(); $dataObject->load($this->loadData()); $this->setData($dataObject); //Создаем сейвер $saver = $this->getSaver(); //Устанавливаем его режим $saver->setMode($mode); $saver->setDataDescription($this->getDataDescription()); $saver->setData($this->getData()); if ($saver->validate() === true) { $saver->setFilter($this->getFilter()); $saver->save(); $result = $saver->getResult(); } else { //выдвигается exception который перехватывается в методе save throw new SystemException('ERR_VALIDATE_FORM', SystemException::ERR_WARNING, $this->saver->getErrors()); } //Если у нас режим вставки и определена колонка для порядка следования, изменяем порядок следования if (($orderColumn = $this->getOrderColumn()) && $mode == self::COMPONENT_TYPE_FORM_ADD) { $this->addFilterCondition([$this->getPK() . '!=' . $result]); $request = 'UPDATE ' . $this->getTableName() . ' SET ' . $orderColumn . '=' . $orderColumn . '+1 ' . $this->dbh->buildWhereCondition($this->getFilter()); $this->dbh->modify($request); } return $result; }
/** * Build tab of rights. * * @param int $id Division ID. * * @note By creation of new division use parent ID. */ private function buildRightsTab($id) { $builder = new Builder($this->getTitle()); //получаем информацию о всех группах имеющихся в системе $groups = $this->dbh->select('user_groups', ['group_id', 'group_name']); $groups = convertDBResult($groups, 'group_id'); //создаем матриц //название группы/перечень прав foreach (array_keys($groups) as $groupID) { $res[] = ['right_id' => 0, 'group_id' => $groupID]; } $resultData = new Data(); $resultData->load($res); $builder->setData($resultData); $rightsField = $resultData->getFieldByName('right_id'); $groupsField = $resultData->getFieldByName('group_id'); //создаем переменную содержащую идентификторы групп в которые входит пользователь $data = $this->dbh->select('share_access_level', ['group_id', 'right_id'], ['smap_id' => $id]); if ($data) { $data = convertDBResult($data, 'group_id', true); for ($i = 0; $i < $resultData->getRowCount(); $i++) { //если установлены права для группы - изменяем в объекте данных if (isset($data[$groupsField->getRowData($i)])) { $rightsField->setRowData($i, $data[$groupsField->getRowData($i)]['right_id']); } $groupsField->setRowProperty($i, 'group_id', $groupsField->getRowData($i)); } } for ($i = 0; $i < $resultData->getRowCount(); $i++) { $groupsField->setRowProperty($i, 'group_id', $groupsField->getRowData($i)); $groupsField->setRowData($i, $groups[$groupsField->getRowData($i)]['group_name']); } $resultDD = new DataDescription(); $fd = new FieldDescription('group_id'); $fd->setSystemType(FieldDescription::FIELD_TYPE_STRING); $fd->setMode(FieldDescription::FIELD_MODE_READ); $fd->setLength(30); $resultDD->addFieldDescription($fd); $fd = new FieldDescription('right_id'); $fd->setSystemType(FieldDescription::FIELD_TYPE_SELECT); $data = $this->dbh->select('user_group_rights', ['right_id', 'right_const as right_name']); $data = array_map(function ($a) { $a["right_name"] = translate("TXT_" . $a["right_name"]); return $a; }, $data); $data[] = ['right_id' => 0, 'right_name' => $this->translate('TXT_NO_RIGHTS')]; $fd->loadAvailableValues($data, 'right_id', 'right_name'); $resultDD->addFieldDescription($fd); $builder->setDataDescription($resultDD); $builder->build(); $field = new Field('page_rights'); for ($i = 0; $i < count(E()->getLanguage()->getLanguages()); $i++) { $field->addRowData($builder->getResult()); } $this->getData()->addField($field); }
/** * Player for embedding in text areas */ protected function embedPlayer() { $sp = $this->getStateParams(); list($uplId) = $sp; $fileInfo = $this->dbh->select('share_uploads', ['upl_path', 'upl_name', 'upl_title', 'upl_internal_type', 'upl_mime_type', 'upl_data'], ['upl_id' => intval($uplId), 'upl_internal_type' => \Energine\share\gears\FileRepoInfo::META_TYPE_VIDEO]); if (!$fileInfo) { throw new SystemException('ERROR_NO_VIDEO_FILE', SystemException::ERR_404); } // Using array_values to transform associative index to key index list($file, $name, $title, $type, $mime, $data) = array_values($fileInfo[0]); $dd = new DataDescription(); foreach (['file' => FieldDescription::FIELD_TYPE_STRING, 'name' => FieldDescription::FIELD_TYPE_STRING, 'title' => FieldDescription::FIELD_TYPE_STRING, 'type' => FieldDescription::FIELD_TYPE_STRING, 'mime' => FieldDescription::FIELD_TYPE_STRING, 'data' => FieldDescription::FIELD_TYPE_TEXT] as $fName => $fType) { $fd = new FieldDescription($fName); $fd->setType($fType); $dd->addFieldDescription($fd); } $this->setBuilder(new SimpleBuilder()); $this->setDataDescription($dd); $d = new Data(); $d->load([compact('file', 'name', 'title', 'type', 'mime', 'data')]); $this->setData($d); $this->js = $this->buildJS(); /** * If we want to use custom embed player we need to redefine embed_player.xslt in module transformers dir */ $fn = 'embed_player.xslt'; if (file_exists($file = sprintf(SITE_DIR . XSLTTransformer::MAIN_TRANSFORMER_DIR, E()->getSiteManager()->getCurrentSite()->folder) . $fn)) { E()->getController()->getTransformer()->setFileName($fn); } else { E()->getController()->getTransformer()->setFileName('core/modules/share/transformers/embed_player.xslt', true); } }
/** * Save data. * * @param array $data Data. * @return mixed * * @throws SystemException 'ERR_VALIDATE_FORM' */ protected function saveData(&$data) { //Обрабатываем аплоадсы $result = false; if (isset($_FILES) && !empty($_FILES)) { list($dbName, $tName) = QAL::getFQTableName($this->getTableName(), true); if (isset($_FILES[$phpTableName = $dbName . '_' . $tName])) { $fileData = []; //Переворачиваем пришедший массив в удобный для нас вид foreach ($_FILES[$phpTableName] as $fParam => $fileInfo) { foreach ($fileInfo as $fName => $val) { $fileData[$fName][$fParam] = $val; } } $uploader = new FileUploader(); foreach ($fileData as $fieldName => $fileInfo) { //Завантажувати лише якщо файл дійсно завантажили if (!empty($fileInfo['name']) && $fileInfo['size'] > 0) { $uploader->setFile($fileInfo); $uploader->upload('uploads/forms'); $data[$this->getTableName()][$fieldName] = $uploader->getFileObjectName(); $uploader->cleanUp(); } } } } //создаем объект описания данных $dataDescriptionObject = new DataDescription(); //получаем описание полей для метода $configDataDescription = $this->getConfig()->getStateConfig($this->getPreviousState()); //если в конфиге есть описание полей для метода - загружаем их if (isset($configDataDescription->fields)) { $dataDescriptionObject->loadXML($configDataDescription->fields); } //Создаем объект описания данных взятых из БД $DBDataDescription = new DataDescription(); //Загружаем в него инфу о колонках $DBDataDescription->load($this->loadDataDescription()); $this->setDataDescription($dataDescriptionObject->intersect($DBDataDescription)); $this->getDataDescription()->getFieldDescriptionByName('form_date')->removeProperty('pattern'); $dataObject = new Data(); foreach ($data[$this->getTableName()] as $key => $value) { if (is_scalar($value)) { $data[$this->getTableName()][$key] = strip_tags($value); } } $dataObject->load($data); $this->setData($dataObject); //Создаем сейвер $this->saver = new Saver(); //Устанавливаем его режим $this->saver->setMode(self::COMPONENT_TYPE_FORM_ADD); $this->saver->setDataDescription($this->getDataDescription()); $this->saver->setData($this->getData()); if ($this->saver->validate() === true) { $this->saver->setFilter($this->getFilter()); $this->saver->save(); $result = $this->saver->getResult(); } else { //выдвигается пустой exception который перехватывается в методе save //выдвигается exception который перехватывается в методе save throw new SystemException('ERR_VALIDATE_FORM', SystemException::ERR_WARNING, $this->saver->getErrors()); } return $result; }
protected function main() { E()->getController()->getTransformer()->setFileName($this->getParam('index.xslt'), true); $dd = new DataDescription(); $dd->addFieldDescription(new FieldDescription('path')); $this->setDataDescription($dd); $d = new Data(); $sitemaps = []; $siteinfo = E()->getSiteManager()->getCurrentSite(); if (!$siteinfo->isIndexed) { throw new SystemException('ERR_404', SystemException::ERR_404); } $sitePath = $siteinfo->base; $fullPath = $this->request->getPath(1, true); if ($this->dbh->tableExists('seo_sitemap_videos')) { $this->pdoDB->query('SELECT SQL_CALC_FOUND_ROWS videos_id FROM seo_sitemap_videos WHERE site_id = ' . $siteinfo->id . ' ORDER BY videos_date DESC'); $rows_info = $this->pdoDB->query('SELECT FOUND_ROWS() as num_rows'); $rows_info = $rows_info->fetch(); $totalMaps = ceil($rows_info[0] / $this->maxVideos); for ($i = 1; $i <= $totalMaps; $i++) { array_push($sitemaps, ['path' => $sitePath . $fullPath . 'videomap/' . $i]); } } array_push($sitemaps, ['path' => $sitePath . $fullPath . 'map']); $d->load($sitemaps); $this->setData($d); $this->setBuilder(new SimpleBuilder()); }