public function __construct() { parent::__construct(); /* * Загружаем инфомацию о группах пользователей в структуру вида: * array( * $group_id => array(group info) * ); */ $this->groups = convertDBResult($this->dbh->select('user_groups'), 'group_id', true); }
/** * Find nearest parent with branding. * * @return int */ private function findNearestParentBrandID() { //список родителей $parents = array_keys(E()->getMap()->getParents($this->document->getID())); //добавили текущий раздел array_push($parents, $this->document->getID()); //делаем выборку брендингов $d = convertDBResult($this->dbh->select('share_sitemap', array('smap_id', 'brand_id'), array('smap_id' => $parents)), 'smap_id', true); //Результирующий массив $res = array(); //проходимся по списку родителей формируя отсортированный список "идент раздела"=>"идент бренда" foreach ($parents as $smapID) { if (!is_null($d[$smapID]['brand_id'])) { $res[$smapID] = $d[$smapID]['brand_id']; } } //возвращаем последний идент бренда return array_pop($res); }
/** * @copydoc DataSet::main */ protected function main() { parent::main(); //Сначала проверили есть ли свой код баннера $result = $this->dbh->select(AdsManager::TABLE_NAME, true, array('smap_id' => $this->document->getID()), array('smap_id' => QAL::DESC), 1); //Если нет собственного - ищем у родителей if (!is_array($result)) { $result = false; //Список идентфикаторов родителей в порядке увелечения уровня $IDs = array_reverse(array_keys(E()->getMap()->getParents($this->document->getID()))); $tmp = $this->dbh->select(AdsManager::TABLE_NAME, true, array('smap_id' => $IDs)); if (is_array($tmp)) { $tmp = convertDBResult($tmp, 'smap_id'); } //перебираем записи родителей foreach ($IDs as $id) { //если есть родитель с рекламой if (isset($tmp[$id])) { $result = array($tmp[$id]); //дальше смотреть нет смысла break; } } } if (is_array($result)) { //We don't need smap_id, so don't write it to Data unset($result[0]['smap_id']); foreach ($result[0] as $key => $value) { $fd = new FieldDescription($key); if (in_array($key, array('ad_id'))) { $fd->setType(FieldDescription::FIELD_TYPE_INT); } else { $fd->setType(FieldDescription::FIELD_TYPE_TEXT); } $this->getDataDescription()->addFieldDescription($fd); } $this->getData()->load($result); } }
/** * Add information about users. * * @param array $data Data. * @return array */ private function addUsersInfo($data) { if ($data && is_array($data)) { $usersInfo = $this->getUsersByComments($data); $usersInfo = convertDBResult($usersInfo, 'u_id'); foreach ($data as &$item) { $user = $usersInfo[$item['u_id']]; $item['u_fullname'] = $user['u_fullname']; } } return $data; }
/** * 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(); }
/** * Get information about sections. * * @param int|array $id Section ID or array of IDs. * @return array */ private function getSitemapData($id) { if (!is_array($id)) { $id = [$id]; } if ($diff = array_diff($id, array_keys($this->info))) { $ids = implode(',', $diff); $result = convertDBResult($this->dbh->select('SELECT s.*, st.* FROM share_sitemap s LEFT JOIN share_sitemap_translation st ON s.smap_id = st.smap_id WHERE st.lang_id = %s AND s.site_id = %s AND s.smap_id IN (' . $ids . ')', $this->langID, $this->siteID), 'smap_id', true); if ($result) { $result = array_map([$this, 'preparePageInfo'], $result); $this->info += $result; } } else { $result = []; foreach ($this->info as $key => $value) { if (in_array($key, $diff)) { $result[$key] = $value; } } } return $result; }
protected function createData() { $result = parent::createData(); $id = $this->getFilter(); $id = !empty($id) && is_array($id) ? current($id) : false; if ($this->getType() != self::COMPONENT_TYPE_LIST && $id) { //создаем переменную содержащую идентификторы групп в которые входит пользователь $f = new Field('group_id'); $result->addField($f); $data = $this->dbh->select('user_user_groups', array('group_id'), array('u_id' => $id)); if (!empty($data)) { $f->addRowData(array_keys(convertDBResult($data, 'group_id', true))); } else { $f->setData(array()); } } return $result; }
/** * Show news that correspond to specific tag. * * @note If tag is not exist then clean all previously received data. */ protected function tag() { $tagID = $this->getStateParams(true); $tagID = (int) $tagID['tagID']; $newsIDs = $this->dbh->select($this->dbh->getTagsTablename($this->getTableName()), 'news_id', array('tag_id' => $tagID)); if (is_array($newsIDs)) { $newsIDs = array_keys(convertDBResult($newsIDs, 'news_id', true)); $this->addFilterCondition(array($this->getTableName() . '.news_id' => $newsIDs)); $tagName = $this->dbh->getScalar('SELECT tag_name FROM share_tags LEFT JOIN share_tags_translation USING(tag_id) WHERE (lang_id = %s) AND (tag_id = %s)', $this->document->getLang(), $tagID); $pageTitle = $this->translate('TXT_NEWS_BY_TAG') . ': ' . $tagName; E()->getDocument()->componentManager->getBlockByName('breadCrumbs')->addCrumb(null, $pageTitle); E()->getDocument()->setProperty('title', $pageTitle); } $this->main(); if ($newsIDs === true) { $this->setData(new Data()); } if ($this->pager) { $this->pager->setProperty('additional_url', 'tag/' . $tagID . '/'); } }
/** * Modify data set by adding the values from "m2m" table. * @param array $data Data. * @return array|false */ protected function modify($data) { if (!is_array($data)) { return $data; } //Перечень мультиполей $multiFields = $this->getDataDescription()->getFieldDescriptionsByType(FieldDescription::FIELD_TYPE_MULTI); //Loading m2m data if (!empty($multiFields)) { $m2mData = []; $primaryKeyName = $this->getPK(); $pks = simplifyDBResult($data, $primaryKeyName); //create storage array //array($MultiFieldName => array($pk => $values)) foreach ($multiFields as $mfd) { $relInfo = $mfd->getPropertyValue('key'); if (is_array($relInfo) && $this->dbh->tableExists($relInfo['tableName'])) { $res = $this->dbh->select($relInfo['tableName'], true, [$primaryKeyName => $pks]); if ($res) { foreach ($res as $row) { $pk = $row[$relInfo['fieldName']]; unset($row[$relInfo['fieldName']]); $m2mData[$mfd->getName()][$pk][] = current($row); } } } else { foreach (array_keys($data) as $key) { if (isset($data[$key][$mfd->getName()]) && $data[$key][$mfd->getName()]) { $data[$key][$mfd->getName()] = explode(',', $data[$key][$mfd->getName()]); } } } } //Проходимся по всем данным foreach ($data as $key => $row) { //потом по multi полям foreach ($m2mData as $fieldName => $m2mValues) { //Если в списке полей данных существует мультиполе с этим именем if (array_key_exists($fieldName, $row)) { // foreach ($m2mValues as $pk => $values) { if ($row[$primaryKeyName] == $pk) { $data[$key][$fieldName] = $values; } } } } } } $lookupField = $this->getDataDescription()->getFieldDescriptionsByType(FieldDescription::FIELD_TYPE_LOOKUP); if (!empty($lookupField)) { //Готовим инфу для получения данных их связанных таблиц foreach ($lookupField as $valueFieldName => $valueField) { $relInfo = $valueField->getPropertyValue('key'); if (is_array($relInfo)) { $langTable = $this->dbh->getTranslationTablename($relInfo['tableName']); $relations[$valueFieldName] = ['table' => !$langTable ? $relInfo['tableName'] : $langTable, 'field' => $relInfo['fieldName'], 'lang' => $langTable ? E()->getLanguage()->getCurrent() : false, 'valueField' => substr($relInfo['fieldName'], 0, strrpos($relInfo['fieldName'], '_')) . '_name']; $cond = [$relations[$valueFieldName]['field'] => simplifyDBResult($data, $valueFieldName)]; if ($relations[$valueFieldName]['lang']) { $cond['lang_id'] = $relations[$valueFieldName]['lang']; } $values[$valueFieldName] = convertDBResult($this->dbh->select($relations[$valueFieldName]['table'], [$relations[$valueFieldName]['field'], $relations[$valueFieldName]['valueField']], $cond), $relations[$valueFieldName]['field'], true); } } unset($lookupField, $langTable, $relInfo); foreach ($data as $key => $row) { foreach ($row as $name => $value) { if (in_array($name, array_keys($relations)) && is_array($values[$name]) && array_key_exists($value, $values[$name])) { $data[$key][$name] = ['id' => $value, 'value' => $values[$name][$value][$relations[$name]['valueField']]]; } } } } return $data; }
/** * @copydoc LinkingEditor::changeOrder */ protected function changeOrder($direction) { if (!$this->getOrderColumn()) { //Если не задана колонка для пользовательской сортировки то на выход throw new SystemException('ERR_NO_ORDER_COLUMN', SystemException::ERR_DEVELOPER); } $currentID = $this->getStateParams(); list($currentID) = $currentID; //Определяем order_num текущей страницы $currentOrderNum = $this->dbh->getScalar('SELECT ' . $this->getOrderColumn() . ' ' . 'FROM ' . $this->getTableName() . ' ' . 'WHERE ' . $this->getPK() . ' = %s', $currentID); $orderDirection = $direction == Grid::DIR_DOWN ? QAL::ASC : QAL::DESC; $baseFilter = $this->getFilter(); if (!empty($baseFilter)) { $baseFilter = ' AND ' . str_replace('WHERE', '', $this->dbh->buildWhereCondition($this->getFilter())); } else { $baseFilter = ' AND smap_id = ' . $this->document->getID() . ' '; } //Определяем идентификатор записи которая находится рядом с текущей $request = 'SELECT ' . $this->getPK() . ' as neighborID, ' . $this->getOrderColumn() . ' as neighborOrderNum ' . 'FROM ' . $this->getTableName() . ' ' . 'WHERE ' . $this->getOrderColumn() . ' ' . $direction . ' ' . $currentOrderNum . ' ' . $baseFilter . 'ORDER BY ' . $this->getOrderColumn() . ' ' . $orderDirection . ' Limit 1'; $data = convertDBResult($this->dbh->select($request), 'neighborID'); if ($data) { extract(current($data)); $this->dbh->beginTransaction(); $this->dbh->modify(QAL::UPDATE, $this->getTableName(), array($this->getOrderColumn() => $neighborOrderNum), array($this->getPK() => $currentID)); $this->dbh->modify(QAL::UPDATE, $this->getTableName(), array($this->getOrderColumn() => $currentOrderNum), array($this->getPK() => $neighborID)); $this->dbh->commit(); } $b = new JSONCustomBuilder(); $b->setProperties(array('result' => true, 'dir' => $direction)); $this->setBuilder($b); }
/** * @copydoc Grid::changeOrder */ protected function changeOrder($direction) { $id = $this->getStateParams(); list($id) = $id; if (!$this->recordExists($id)) { throw new SystemException('ERR_404', SystemException::ERR_404); } $order = $this->getOrder(); if ($direction == Grid::DIR_UP) { $order[key($order)] = $order[key($order)] == QAL::ASC ? QAL::DESC : QAL::ASC; } $PID = $this->dbh->getScalar($this->getTableName(), ['smap_pid'], ['smap_id' => $id]); if (!is_null($PID)) { $PID = ' = ' . $PID; } else { $PID = 'IS NULL'; } $orderFieldName = key($order); $request = sprintf('SELECT %s, %s FROM %s WHERE %s %s= ( SELECT %s FROM %s WHERE %s = %s ) AND smap_pid %s %s LIMIT 2 ', $this->getPK(), $orderFieldName, $this->getTableName(), $orderFieldName, $direction, $orderFieldName, $this->getTableName(), $this->getPK(), $id, $PID, $this->dbh->buildOrderCondition($order)); $result = $this->dbh->select($request); if (!$result || sizeof($result) < 2) { throw new SystemException('ERR_CANT_MOVE', SystemException::ERR_NOTICE); } $result = convertDBResult($result, $this->getPK(), true); /** * @todo Тут нужно что то пооптимальней придумать для того чтобы осуществить операцию переноса значений между двумя элементами массива * $a = $b; * $b =$a; */ $keys = array_keys($result); $data = []; $c = $result[current($keys)]; $data[current($keys)] = $result[next($keys)]; $data[current($keys)] = $c; foreach ($data as $id2 => $value) { $order = $value['smap_order_num']; $this->dbh->modify(QAL::UPDATE, $this->getTableName(), [$orderFieldName => $order], [$this->getPK() => $id2]); if ($id2 != $id) { $result = $id2; } } $b = new JSONCustomBuilder(); $b->setProperties(['result' => true, 'dir' => $direction, 'nodeID' => $result]); $this->setBuilder($b); }