energine
[ class tree: energine ] [ index: energine ] [ all elements ]

Source for file DivisionEditor.class.php

Documentation is available at DivisionEditor.class.php

  1. <?php
  2.  
  3. /**
  4.  * Содержит класс DivisionEditor
  5.  *
  6.  * @package energine
  7.  * @subpackage share
  8.  * @author dr.Pavka
  9.  * @copyright Energine 2006
  10.  * @version $Id$
  11.  */
  12.  
  13. //require_once('core/modules/share/components/Grid.class.php');
  14.  
  15. /**
  16.  * Редактор разделов
  17.  *
  18.  * @package energine
  19.  * @subpackage share
  20.  * @author dr.Pavka
  21.  * @final
  22.  */
  23. final class DivisionEditor extends Grid {
  24.     /**
  25.      * Редактор шаблонов
  26.      *
  27.      * @var TemplateEditor 
  28.      * @access private
  29.      */
  30.     private $templateEditor;
  31.  
  32.     /**
  33.      * Редактор переводов
  34.      *
  35.      * @var TranslationEditor 
  36.      * @access private
  37.      */
  38.     private $transEditor;
  39.     /**
  40.      * Редактор пользователей
  41.      * 
  42.      * @var UserEditor 
  43.      * @access private
  44.      */
  45.     private $userEditor;
  46.     /**
  47.      * Редактор ролей
  48.      * 
  49.      * @var RoleEditor 
  50.      * @access private
  51.      */
  52.     private $roleEditor;
  53.     /**
  54.      * Редактор языков
  55.      * 
  56.      * @var LanguageEditor 
  57.      * @access private
  58.      */
  59.     private $langEditor;
  60.  
  61.     /**
  62.      * Конструктор класса
  63.      *
  64.      * @return void 
  65.      */
  66.     public function __construct($name$moduleDocument $document,  array $params null{
  67.         parent::__construct($name$module$document,  $params);
  68.         $this->setTableName('share_sitemap');
  69.         $this->setTitle($this->translate('TXT_DIVISION_EDITOR'));
  70.         $this->setOrder(array('smap_order_num'=>QAL::ASC));
  71.  
  72.         $this->setParam('recordsPerPage'false);
  73.         $this->setOrderColumn('smap_order_num');
  74.         //$this->setFilter(array('smap_pid'=>QAL::EMPTY_STRING));
  75.     }
  76.  
  77.     /**
  78.      * Метод выводит форму назначения прав
  79.      *
  80.      * @return void 
  81.      * @access protected
  82.      */
  83.  
  84.     protected function setPageRights({
  85.         $this->setType(self::COMPONENT_TYPE_FORM);
  86.         //$this->addCrumb('TXT_SET_RIGHTS');
  87.         $this->setDataSetAction('save-rights');
  88.         $this->prepare();
  89.     }
  90.  
  91.     /**
  92.      * Строит вкладку прав
  93.      *
  94.      * @return DOMNode 
  95.      * @access private
  96.      */
  97.  
  98.     private function buildRightsTab({
  99.         $builder new SimpleBuilder($this->getTitle());
  100.  
  101.         $id $this->getFilter();
  102.         $id (!empty($id))?current($id):false;
  103.  
  104.         //получаем информацию о всех группах имеющихся в системе
  105.         $groups $this->dbh->select('user_groups'array('group_id''group_name''group_default_rights'));
  106.         $groups convertDBResult($groups'group_id');
  107.         //создаем матрицу
  108.         //название группы/перечень прав
  109.         foreach ($groups as $groupID=>$groupInfo{
  110.             $res[array('right_id'=>($this->getAction(== 'add')?$groupInfo['group_default_rights']:0'group_id'=>$groupID);
  111.         }
  112.  
  113.         $resultData new Data();
  114.         $resultData->load($res);
  115.         $builder->setData($resultData);
  116.  
  117.         $rightsField $resultData->getFieldByName('right_id');
  118.         $groupsField $resultData->getFieldByName('group_id');
  119.  
  120.         if ($id{
  121.             //создаем переменную содержащую идентификторы групп в которые входит пользователь
  122.             $data $this->dbh->select('share_access_level'truearray('smap_id'=>$id));
  123.             if(is_array($data)) {
  124.                 $data convertDBResult($data'group_id'true);
  125.  
  126.                 for ($i=0$i<$resultData->getRowCount()$i++{
  127.  
  128.                     //если установлены права для группы  - изменяем в объекте данных
  129.                     if (isset($data[$groupsField->getRowData($i)])) {
  130.                         $rightsField->setRowData($i$data[$groupsField->getRowData($i)]['right_id']);
  131.                     }
  132.  
  133.                     $groupsField->setRowProperty($i'group_id'$groupsField->getRowData($i));
  134.                 }
  135.             }
  136.         }
  137.  
  138.         for ($i=0$i<$resultData->getRowCount()$i++{
  139.             $groupsField->setRowProperty($i'group_id'$groupsField->getRowData($i));
  140.             $groupsField->setRowData($i$groups[$groupsField->getRowData($i)]['group_name']);
  141.         }
  142.  
  143.         $resultDD new DataDescription();
  144.         $fd new FieldDescription('group_id');
  145.         $fd->setSystemType(FieldDescription::FIELD_TYPE_STRING);
  146.         $fd->setMode(FieldDescription::FIELD_MODE_READ);
  147.         $fd->setLength(30);
  148.         $resultDD->addFieldDescription($fd);
  149.  
  150.         $fd new FieldDescription('right_id');
  151.         $fd->setSystemType(FieldDescription::FIELD_TYPE_SELECT);
  152.         $data $this->dbh->select('user_group_rights'array('right_id''right_const as right_name'));
  153.         $data array_map(create_function('$a''$a["right_name"] = DBWorker::_translate("TXT_".$a["right_name"]); return $a;')$data);
  154.         $data[array('right_id'=>0'right_name'=>$this->translate('TXT_NO_RIGHTS'));
  155.  
  156.         $fd->loadAvailableValues($data'right_id''right_name');
  157.         $resultDD->addFieldDescription($fd);
  158.  
  159.         $builder->setDataDescription($resultDD);
  160.         $builder->build();
  161.         
  162.         return $builder->getResult();
  163.     }
  164.  
  165.     /**
  166.       * Для setRole создаем свое описание данных
  167.       * Для поля smap_pid формируется Дерево разделов
  168.       *
  169.       * @return DataDescription 
  170.       * @access protected
  171.       */
  172.  
  173.     protected function createDataDescription({
  174.         $result parent::createDataDescription();
  175.  
  176.         //для редактирования и добавления нужно сформировать "красивое дерево разделов"
  177.         if (in_array($this->getAction()array('add''edit'))) {
  178.             $fd $result->getFieldDescriptionByName('smap_pid');
  179.             $fd->setType(FieldDescription::FIELD_TYPE_STRING);
  180.             $fd->setMode(FieldDescription::FIELD_MODE_READ);
  181.             $result->getFieldDescriptionByName('smap_name')->removeProperty('nullable');
  182.         }
  183.         else {
  184.             //Для режима списка нам нужно выводить не значение а ключ
  185.             if ($this->getType(== self::COMPONENT_TYPE_LIST{
  186.                 $smapPIDFieldDescription $result->getFieldDescriptionByName('smap_pid');
  187.                 if ($smapPIDFieldDescription{
  188.                     $smapPIDFieldDescription->setType(FieldDescription::FIELD_TYPE_INT);
  189.                 }
  190.             }
  191.             if ($this->getAction(== 'getRawData'{
  192.                 $field new FieldDescription('smap_segment');
  193.                 $field->setType(FieldDescription::FIELD_TYPE_STRING);
  194.                 $field->setProperty('tableName'$this->getTableName());
  195.                 $result->addFieldDescription($field);
  196.             }
  197.         }
  198.         return $result;
  199.     }
  200.  
  201.     /**
  202.      * Добавляет данные об УРЛ
  203.      *
  204.      * @return array 
  205.      * @access protected
  206.      */
  207.  
  208.     protected function loadData({
  209.         $result parent::loadData();
  210.         if($result && $this->getAction(== 'getRawData'{
  211.             //Используется GLOBALS поскольку нет другой возможности передать 
  212.             //в runtime created function посторонее значение 
  213.             $GLOBALS['__SMAP2ICONS'convertDBResult($this->dbh->selectRequest('
  214.                 SELECT DISTINCT t.tmpl_icon, s.smap_id FROM `share_sitemap` s
  215.                 LEFT JOIN share_templates t ON t.tmpl_id=s.tmpl_id
  216.             ')'smap_id'true);
  217.             
  218.             $result array_map(
  219.                 create_function(
  220.                     '$val'
  221.                     '
  222.                     $val["smap_segment"] = SiteMap::getInstance()->getURLByID($val["smap_id"]);
  223.                     $val["tmpl_icon"] = $GLOBALS["__SMAP2ICONS"][$val["smap_id"]]["tmpl_icon"]; 
  224.                     return $val;
  225.                     '
  226.                 )
  227.             $result);
  228.             unset($GLOBALS['__SMAP2ICONS']);
  229.         }
  230.  
  231.         return $result;
  232.     }
  233.     
  234.     protected function getRawData($baseMethod self::DEFAULT_ACTION_NAME){
  235.          try {
  236.             $this->setParam('onlyCurrentLang'true);
  237.             $this->config->setCurrentMethod($baseMethod);
  238.             $this->setBuilder(new JSONDivBuilder());
  239.             
  240.             $this->setDataDescription($this->createDataDescription());
  241.             $this->getBuilder()->setDocumentId($this->document->getID());
  242.             $this->getBuilder()->setDataDescription($this->getDataDescription());
  243.             
  244.             $data $this->createData();
  245.             if ($data instanceof Data{
  246.                 $this->setData($data);
  247.                 $this->getBuilder()->setData($this->getData());
  248.             }
  249.  
  250.             if ($this->getBuilder()->build()) {
  251.                 $result $this->getBuilder()->getResult();
  252.             }
  253.             else {
  254.                 $result $this->getBuilder()->getErrors();
  255.             }
  256.  
  257.         }
  258.         catch (Exception $e){
  259.             $message['errors'][array('message'=>$e->getMessage().current($e->getCustomMessage()));
  260.             $result json_encode(array_merge(array('result'=>false'header'=>$this->translate('TXT_SHIT_HAPPENS'))$message));
  261.         }
  262.         $this->response->setHeader('Content-Type''text/javascript; charset=utf-8');
  263.         $this->response->write($result);
  264.         $this->response->commit();    
  265.     }
  266.  
  267.     /**
  268.      * Подменяем построитель для метода setPageRights
  269.      *
  270.      * @return Builder 
  271.      * @access protected
  272.      */
  273.  
  274.     protected function prepare({
  275.         parent::prepare();
  276.         $actionParams $this->getActionParams();
  277.         
  278.         if(in_array($this->getAction()array('add''edit'))){
  279.             $field new Field('page_rights');
  280.             $rightsData $this->buildRightsTab();
  281.             
  282.             for ($i 0$i count(Language::getInstance()->getLanguages())$i++{
  283.                 $field->addRowData(
  284.                     $rightsData
  285.                 );
  286.             }
  287.             $this->getData()->addField($field);
  288.             $this->addTranslation('ERR_NO_DIV_NAME');
  289.         }
  290.                 
  291.         if ($this->getAction(== 'edit'{
  292.             $this->addAttFilesField(
  293.                 'share_sitemap_uploads',
  294.                 $this->dbh->selectRequest('
  295.                     SELECT files.upl_id, upl_path, upl_name
  296.                     FROM `share_sitemap_uploads` s2f
  297.                     LEFT JOIN `share_uploads` files ON s2f.upl_id=files.upl_id
  298.                     WHERE smap_id = %s
  299.                 '$this->getData()->getFieldByName('smap_id')->getRowData(0))
  300.             );
  301.             $field $this->getData()->getFieldByName('smap_pid');
  302.             $smapSegment '';
  303.             if($field->getRowData(0!== null{
  304.                 $smapSegment Sitemap::getInstance()->getURLByID($field->getRowData(0));
  305.             }
  306.             $smapName simplifyDBResult($this->dbh->select($this->getTranslationTableName()array('smap_name')array('smap_id' => $field->getRowData(0)'lang_id' => $this->document->getLang()))'smap_name'true);
  307.  
  308.             for ($i 0$i count(Language::getInstance()->getLanguages())$i++{
  309.                 $field->setRowProperty($i'data_name'$smapName);
  310.                 $field->setRowProperty($i'segment'$smapSegment);
  311.             }
  312.  
  313.         }
  314.         elseif ($this->getAction(== 'add'{
  315.             $this->addAttFilesField('share_sitemap_uploads');
  316.             if(
  317.             !empty($actionParams
  318.             && 
  319.             ($actionParams[0!= Sitemap::getInstance()->getDefault())
  320.             ){
  321.                 $field $this->getData()->getFieldByName('smap_pid');
  322.                 $smapSegment Sitemap::getInstance()->getURLByID($actionParams[0]);
  323.     
  324.                 $res $this->dbh->select($this->getTranslationTableName()array('smap_name')array('smap_id' => $actionParams[0]'lang_id' => $this->document->getLang()));
  325.                 if (!empty($res)) {
  326.                     $name simplifyDBResult($res'smap_name'true);
  327.                     for ($i 0$i count(Language::getInstance()->getLanguages())$i++{
  328.                         $field->setRowData($i$actionParams[0]);
  329.                         $field->setRowProperty($i'data_name'$name);
  330.                         $field->setRowProperty($i'segment'$smapSegment);
  331.                     }
  332.                 }
  333.             }
  334.         }
  335.     }
  336.  
  337.     /**
  338.      * Переопределенный внешний метод сохранения
  339.      * добавлено значение урла страницы
  340.      * Вызывает внутренний метод сохранения saveData(), который и производит собственно все действия
  341.      *
  342.      * @return void 
  343.      * @access protected
  344.      */
  345.  
  346.     protected function save({
  347.         $transactionStarted $this->dbh->beginTransaction();
  348.         try {
  349.             $result $this->saveData();
  350.             if (is_int($result)) {
  351.                 $mode 'insert';
  352.                 $id $result;
  353.                 /*Тут пришлось пойти на извращаения для получения УРЛа страницы, поскольку новосозданная страница еще не присоединена к дереву*/
  354.                 $smapPID simplifyDBResult($this->dbh->select('share_sitemap''smap_pid'array('smap_id'=>$id))'smap_pid'true);
  355.                 $url $_POST[$this->getTableName()]['smap_segment'].'/';
  356.                 if ($smapPID{
  357.                     $url Sitemap::getInstance()->getURLByID($smapPID).$url;
  358.                 }
  359.  
  360.             }
  361.             else {
  362.                 $mode 'update';
  363.                 $id $this->getFilter();
  364.                 $id $id['smap_id'];
  365.                 $url Sitemap::getInstance()->getURLByID($id);
  366.             }
  367.  
  368.  
  369.             $transactionStarted !($this->dbh->commit());
  370.  
  371.             $JSONResponse array(
  372.             'result' => true,
  373.             'url' => $url,
  374.             'mode' => $mode
  375.             );
  376.         }
  377.         catch (FormException $formError{
  378.             $this->dbh->rollback();
  379.             //Формируем JS массив ошибок который будет разбираться на клиенте
  380.             $errors $this->saver->getErrors();
  381.             foreach ($errors as $errorFieldName{
  382.                 $message['errors'][array(
  383.                 'field'=>$this->translate('FIELD_'.strtoupper($errorFieldName)),
  384.                 'message'=>$this->translate($this->saver->getDataDescription()->getFieldDescriptionByName($errorFieldName)->getPropertyValue('message'))
  385.                 );
  386.             }
  387.             $JSONResponse array_merge(array('result'=>false'header'=>$this->translate('TXT_SHIT_HAPPENS'))$message);
  388.         }
  389.         catch (SystemException $e){
  390.             if ($transactionStarted{
  391.                 $this->dbh->rollback();
  392.             }
  393.             $message['errors'][array('message'=>$e->getMessage().current($e->getCustomMessage()));
  394.             $JSONResponse array_merge(array('result'=>false'header'=>$this->translate('TXT_SHIT_HAPPENS'))$message);
  395.  
  396.         }
  397.         $this->response->write(json_encode($JSONResponse));
  398.         $this->response->commit();
  399.     }
  400.     /**
  401.       * Переопределенный метод сохранения
  402.       * Для того чтобы реализовать уникальность smap_default
  403.       *
  404.       * @param array 
  405.       * @return void 
  406.       * @access protected
  407.       */
  408.  
  409.     protected function saveData({
  410.         if (!isset($_POST['right_id']|| !is_array($_POST['right_id'])) {
  411.             throw new SystemException('ERR_BAD_DATA'SystemException::ERR_CRITICAL);
  412.         }
  413.  
  414.         if (isset($_POST[$this->getTableName()]['smap_default']&& $_POST[$this->getTableName()]['smap_default'!== '0'{
  415.             $this->dbh->modify(QAL::UPDATE$this->getTableName()array('smap_default'=>null));
  416.         }
  417.         if(isset($_POST[$this->getTableName()]['smap_redirect_url']&& !empty($_POST[$this->getTableName()]['smap_redirect_url'])){
  418.             $_POST[$this->getTableName()]['smap_redirect_url'str_replace(Request::getInstance()->getBasePath()''$_POST[$this->getTableName()]['smap_redirect_url']);            
  419.         }
  420.         
  421.         //Выставляем фильтр для родительского идентификатора
  422.         $PID $_POST[$this->getTableName()]['smap_pid'];
  423.         if (empty($PID)) {
  424.             $PID null;
  425.         }
  426.         $this->setFilter(array('smap_pid'=>$PID));
  427.  
  428.         $result parent::saveData();
  429.  
  430.         $smapID (is_int($result))?$result:current($this->getFilter());
  431.         $rights $_POST['right_id'];
  432.  
  433.         //Удаляем все предыдущие записи в таблице прав
  434.         $this->dbh->modify(QAL::DELETE 'share_access_level'nullarray('smap_id'=>$smapID));
  435.         foreach ($rights as $groupID => $rightID{
  436.             if ($rightID != ACCESS_NONE{
  437.                 $this->dbh->modify(QAL::INSERT'share_access_level'array('smap_id'=>$smapID'right_id'=>$rightID'group_id'=>$groupID));
  438.             }
  439.         }
  440.  
  441.         //Изменяем smap_modified
  442.         $this->dbh->modify(QAL::UPDATE$this->getTableName()array('smap_modified' => date('Y-m-d H:i:s'))array('smap_id'=>$smapID));
  443.  
  444.         //Удаляем предыдущие записи из таблицы связей с дополнительными файлами
  445.            $this->dbh->modify(QAL::DELETE'share_sitemap_uploads'nullarray('smap_id' => $smapID));
  446.  
  447.            //записываем данные в таблицу share_sitemap_uploads
  448.         if(isset($_POST['uploads']['upl_id'])){
  449.             foreach ($_POST['uploads']['upl_id'as $uplID){
  450.                 $this->dbh->modify(QAL::INSERT'share_sitemap_uploads'array('smap_id' => $smapID'upl_id' => $uplID));
  451.             }
  452.         }
  453.  
  454.         return $result;
  455.     }
  456.  
  457.     protected function edit({
  458.         parent::edit();
  459.         $field $this->getData()->getFieldByName('smap_redirect_url');
  460.         if($field->getRowData(0)){
  461.             $field->setRowData(0Request::getInstance()->getBasePath().$field->getRowData(0));
  462.         }
  463.     }
  464.  
  465.     /**
  466.      * Добавлен перевод для корня дерева разделов
  467.      *
  468.      * @return void 
  469.      * @access protected
  470.      */
  471.  
  472.      protected function main({
  473.         parent::main();
  474.         $this->addTranslation('TXT_DIVISIONS');
  475.      }
  476.  
  477.  
  478.     /**
  479.      * Не позволяет удалить раздел по умолчанию а также системные разделы
  480.      *
  481.      * @param int 
  482.      * @return void 
  483.      * @access protected
  484.      */
  485.  
  486.     protected function deleteData($id{
  487.         $res $this->dbh->select('share_sitemap'array('smap_is_system''smap_default''smap_pid')array($this->getPK()=>$id));
  488.         if (!is_array($res))
  489.         throw new SystemException('ERR_DEV_BAD_DATA'SystemException::ERR_CRITICAL);
  490.  
  491.         list($res$res;
  492.         if ($res['smap_is_system'|| $res['smap_default']{
  493.             throw new SystemException('ERR_DEFAULT_OR_SYSTEM_DIVISION'SystemException::ERR_NOTICE );
  494.         }
  495.  
  496.         $PID $res['smap_pid'];
  497.         if (empty($PID)) {
  498.             $PID null;
  499.         }
  500.  
  501.         $this->setFilter(array('smap_pid'=>$PID));
  502.  
  503.         parent::deleteData($id);
  504.     }
  505.  
  506.  
  507.     /**
  508.      * Для метода setPageRights если раздел который редактируется - системный то дизейблятся вкладки с правами
  509.      * Для метода show слешатся имена разделов
  510.      * Для формы редактирования делается неактивным переключатель smap_default
  511.      *
  512.      * @return DOMNode 
  513.      * @access public
  514.      */
  515.  
  516.     public function build({
  517.         switch ($this->getAction()) {
  518.             case 'showPageToolbar':
  519.                 $result false;
  520.                 // вызываем родительский метод построения
  521.                 $result Component::build();
  522.                 $result->documentElement->appendChild($result->importNode($this->buildJS()true));
  523.                 $tbs $this->getToolbar();
  524.                 if(!empty($tbs))
  525.                     foreach($tbs as $toolbar){
  526.                        $result->documentElement->appendChild($result->importNode($toolbar->build()true));    
  527.                     }
  528.                break;
  529.             case 'showTemplate':
  530.                 $result $this->templateEditor->build();
  531.                 break;
  532.             case 'showTransEditor':
  533.                 $result $this->transEditor->build();
  534.                 break;
  535.             case 'showUserEditor':
  536.                 $result $this->userEditor->build();
  537.                 break;
  538.             case 'showRoleEditor':
  539.                 $result $this->roleEditor->build();
  540.                 break;
  541.             case 'showLangEditor':
  542.                 $result $this->langEditor->build();
  543.                 break;                                                
  544.             default:
  545.                 if ($this->getType(== self::COMPONENT_TYPE_FORM_ALTER {
  546.                     if (($field $this->getData()->getFieldByName('smap_default')) && ($field->getRowData(0)=== true)) {
  547.                         if ($fieldDescription $this->getDataDescription()->getFieldDescriptionByName('smap_default')) {
  548.                             $fieldDescription->setMode(FieldDescription::FIELD_MODE_READ);
  549.                         }
  550.                     }
  551.                 }
  552.                 $result parent::build();
  553.                 /*if ($this->getType() != self::COMPONENT_TYPE_LIST )
  554.                     $result->documentElement->appendChild($this->buildRightsTab());
  555. */
  556.                 break;
  557.         }
  558.  
  559.         return $result;
  560.     }
  561.  
  562.     /**
  563.      * Метод возвращает свойства узла
  564.      *
  565.      * @return void 
  566.      * @access protected
  567.      */
  568.  
  569.     protected function getProperties({
  570.         try {
  571.             $id $_POST['id'];
  572.             $langID $_POST['languageID'];
  573.             if (!$this->recordExists($id)) {
  574.                 throw new SystemException('ERR_404'SystemException::ERR_404);
  575.             }
  576.  
  577.             $this->setFilter(array('smap_id'=>$id'lang_id'=>$langID));
  578.             $result $this->dbh->selectRequest(
  579.                 'SELECT smap_name, smap_pid, smap_order_num, smap_is_final, smap_default, smap_is_system, tmpl_id'.
  580.                 ' FROM share_sitemap s'.
  581.                 ' LEFT JOIN share_sitemap_translation st ON s.smap_id = st.smap_id'.
  582.                 ' WHERE s.smap_id = '.$id.' AND lang_id = '.$langID
  583.             );
  584.             list($result$result;
  585.             $JSONResponse array(
  586.             'result'=>true,
  587.             'data'=>$result,
  588.             );
  589.         }
  590.         catch (SystemException $e){
  591.             $JSONResponse $this->generateError($e->getCode()$e->getMessage());
  592.  
  593.         }
  594.         $this->response->write(json_encode($JSONResponse));
  595.         $this->response->commit();
  596.     }
  597.  
  598.     /**
  599.       * Выводит панель управления страницей
  600.       *
  601.       * @return void 
  602.       * @access protected
  603.       */
  604.  
  605.     protected function showPageToolbar({
  606.         if (!$this->config->getCurrentMethodConfig()) {
  607.             throw new SystemException('ERR_DEV_TOOLBAR_MUST_HAVE_CONFIG'SystemException::ERR_DEVELOPER);
  608.         }
  609.         $this->addToolbar($this->createToolbar());
  610.         if($this->document->isEditable())
  611.             $this->getToolbar('main_toolbar')->getControlByID('editMode')->setState(1);
  612.     }
  613.  
  614.     /**
  615.      * Селектор
  616.      *
  617.      * @return void 
  618.      * @access protected
  619.      */
  620.  
  621.     protected function selector({
  622.         $this->addTranslation('TXT_DIVISIONS');
  623.         $this->prepare();
  624.     }
  625.  
  626.     /**
  627.      * Вывод релактора шаблонов
  628.      *
  629.      * @return void 
  630.      * @access protected
  631.      */
  632.  
  633.     protected function showTemplate({
  634.         $this->request->setPathOffset($this->request->getPathOffset(1);
  635.         $this->templateEditor $this->document->componentManager->createComponent('templateEditor''share''TemplateEditor'null);
  636.         $this->templateEditor->run();
  637.     }
  638.  
  639.     /**
  640.      * Вывод редактора переводов
  641.      *
  642.      * @return void 
  643.      * @access protected
  644.      */
  645.  
  646.     protected function showTransEditor({
  647.         $this->request->setPathOffset($this->request->getPathOffset(1);
  648.         $this->transEditor $this->document->componentManager->createComponent('transEditor''share''TranslationEditor'null);
  649.         $this->transEditor->run();
  650.     }
  651.     /**
  652.      * Вывод редактора пользователей
  653.      *
  654.      * @return void 
  655.      * @access protected
  656.      */
  657.  
  658.     protected function showUserEditor({
  659.         $this->request->setPathOffset($this->request->getPathOffset(1);
  660.         $this->userEditor $this->document->componentManager->createComponent('userEditor''user''UserEditor'null);
  661.         $this->userEditor->run();
  662.     }
  663.     /**
  664.      * Вывод редактора ролей
  665.      *
  666.      * @return void 
  667.      * @access protected
  668.      */
  669.  
  670.     protected function showRoleEditor({
  671.         $this->request->setPathOffset($this->request->getPathOffset(1);
  672.         $this->roleEditor $this->document->componentManager->createComponent('roleEditor''user''RoleEditor'null);
  673.         $this->roleEditor->run();
  674.     }
  675.     /**
  676.      * Вывод редактора языков
  677.      *
  678.      * @return void 
  679.      * @access protected
  680.      */
  681.  
  682.     protected function showLangEditor({
  683.         $this->request->setPathOffset($this->request->getPathOffset(1);
  684.         $this->langEditor $this->document->componentManager->createComponent('langEditor''share''LanguageEditor'null);
  685.         $this->langEditor->run();
  686.     }        
  687.     /**
  688.      * Изменяет порядок следования
  689.      *
  690.      * @param string 
  691.      * @return JSON String
  692.      * @access protected
  693.      */
  694.  
  695.     protected function changeOrder($direction{
  696.         try {
  697.             $id $this->getActionParams();
  698.             list($id$id;
  699.             if (!$this->recordExists($id)) {
  700.                 throw new SystemException('ERR_404'SystemException::ERR_404);
  701.             }
  702.             $order $this->getOrder();
  703.             if ($direction == Grid::DIR_UP{
  704.                 $order[key($order)($order[key($order)== QAL::ASC)?QAL::DESC:QAL::ASC;
  705.             }
  706.  
  707.             //Определяем PID
  708.             $res $this->dbh->select($this->getTableName()array('smap_pid')array('smap_id' => $id));
  709.             $PID simplifyDBResult($res'smap_pid'true);
  710.  
  711.             if (!is_null($PID)) {
  712.                 $PID ' = '.$PID;
  713.             }
  714.             else {
  715.                 $PID 'IS NULL';
  716.             }
  717.  
  718.             $orderFieldName key($order);
  719.             $request sprintf('SELECT %s, %s
  720.                 FROM %s
  721.                 WHERE %s %s= (
  722.                 SELECT %s
  723.                 FROM %s
  724.                 WHERE %s = %s )
  725.                 AND smap_pid %s
  726.                 %s
  727.                 LIMIT 2 ',
  728.             $this->getPK()$orderFieldName,
  729.             $this->getTableName(),
  730.             $orderFieldName$direction,
  731.             $orderFieldName,
  732.             $this->getTableName(),
  733.             $this->getPK()$id,
  734.             $PID,
  735.             $this->dbh->buildOrderCondition($order));
  736.  
  737.             $result $this->dbh->selectRequest($request);
  738.             if ($result === true || sizeof($result)<2{
  739.                 throw new SystemException('ERR_CANT_MOVE'SystemException::ERR_NOTICE);
  740.             }
  741.  
  742.             $result convertDBResult($result$this->getPK()true);
  743.  
  744.             /**
  745.              * @todo Тут нужно что то пооптимальней придумать для того чтобы осуществить операцию переноса значений между двумя элементами массива
  746.              *  $a = $b;
  747.              *  $b =$a;
  748.              */
  749.             $keys array_keys($result);
  750.             $data array();
  751.  
  752.             $c $result[current($keys)];
  753.             $data[current($keys)$result[next($keys)];
  754.             $data[current($keys)$c;
  755.  
  756.             foreach ($data as $id2 => $value{
  757.                 $order $value['smap_order_num'];
  758.                 $this->dbh->modify(QAL::UPDATE$this->getTableName()array($orderFieldName=>$order)array($this->getPK()=>$id2));
  759.                 if ($id2 != $id{
  760.                     $result $id2;
  761.                 }
  762.             }
  763.             $JSONResponse array(
  764.             'result' => true,
  765.             'nodeID' => $result,
  766.             'dir' => $direction
  767.             );
  768.         }
  769.         catch (SystemException $e){
  770.             $JSONResponse $this->generateError($e->getCode()$e->getMessage());
  771.  
  772.         }
  773.         return json_encode($JSONResponse);
  774.     }
  775. }
В создании документации нам помог: phpDocumentor