Author: Gisma (info@gisma.ru) 05.11.2009
Exemplo n.º 1
0
 /**
  * Возвращает дочернее меню для указанного элемента до указанного уровня
  * @param bool $nId обозначает индекс страницы, от которой меню генерировать
  * @param bool $nDepth глубина генерации меню
  * @param bool $bWithAdditional обозначает необходимость подгрузки доп. информации из моделей
  */
 public static function selectMenu($nId = 0, $nDepth = 1, $bWithAdditional = false)
 {
     require_once LIB_PATH . 'kernel/functions/integer.func.php';
     $nDepth = IntegerHelper::toNatural($nDepth);
     $aUrlInfo = self::getCurrentUrlInfo();
     if (empty($nDepth)) {
         return array();
     }
     $aResult = array();
     if ($bWithAdditional) {
         $aResult = Sitemap_PagesOperations::selectChildWithAdditional($nId);
     } else {
         $aResult = Sitemap_PagesOperations::selectChildWithoutAdditional($nId);
     }
     // Перебор по рекурсии, спускаемся ниже, чтобы найти следующие документы
     foreach ($aResult as &$row) {
         if (!empty($row['count'])) {
             $row['aChild'] = self::selectMenu($row['id'], $nDepth - 1, $bWithAdditional);
         } else {
             $row['aChild'] = array();
         }
         // Определяем, что текущий элемент активный
         if (!empty($aUrlInfo)) {
             $isCurrent = SitemapMisc::urlsMatch($aUrlInfo['full_url'], $row['full_url']);
             if ($isCurrent) {
                 $row['active'] = 1;
             }
             if ($row['id'] == $aUrlInfo['id']) {
                 $row['current'] = 1;
             }
         }
     }
     unset($row);
     return $aResult;
 }
Exemplo n.º 2
0
 protected function configureLoginAttempts($perSession, $perHosts)
 {
     $register = new \SystemRegister(UsersLogin::SystemRegisterPath);
     $register->PerSession->value = \IntegerHelper::toNatural($perSession);
     $register->PerHost->value = \IntegerHelper::toNatural($perHosts);
     \SystemRegisterSample::createCache();
 }
Exemplo n.º 3
0
 /**
  * 
  * @param int $id индекс
  * @param string $name системное имя контрола
  * @param string $title тайтл в формах администрирования
  * @param array $additionalConfig доп. данные для донастройки конфига
  * @param mixed $value значение контрола с которым он инициализируется
  * @param CConfigSchema $schema хранит объект текущей схемы
  */
 public function __construct($id, $name, $title, $additionalConfig, $value, $schema)
 {
     $this->id = IntegerHelper::toNatural($id);
     $this->name = $name;
     $this->title = $title;
     $this->schema = $schema;
     $this->config = $additionalConfig;
     $this->value = $value;
 }
Exemplo n.º 4
0
 public function __set($key, $value)
 {
     switch ($key) {
         case 'name':
             $this->szName = htmlspecialchars($value);
             break;
         case 'value':
             $this->value = IntegerHelper::toNatural($value);
             break;
     }
 }
Exemplo n.º 5
0
 /**
  * Возвращает объект схемы на основе индекса из бд
  * @param int $id
  * @return CConfigSchema
  * @throws CConfigException
  */
 public static function getSchemaById($id)
 {
     $id = IntegerHelper::toNatural($id);
     $sql = 'select * from `%s` where `id`="%d"';
     $sql = sprintf($sql, CCONFIG_SCHEMA_TABLE, $id);
     $result = DB::get($sql);
     if (empty($result)) {
         throw new CConfigException('Schema with id="' . $id . '" not found');
     }
     $result = new CConfigSchema($result);
     return $result;
 }
Exemplo n.º 6
0
 public function process()
 {
     if (!empty($this->aUrlInfo['document_name'])) {
         if (!isset($_REQUEST['id'])) {
             throw new Exception('`id` parameter not found in request');
         }
         $id = IntegerHelper::toNatural($_REQUEST['id']);
         if (!$this->disableAutoLoad) {
             $this->loadDocument($id);
         }
     }
     return parent::process();
 }
Exemplo n.º 7
0
 public function generate()
 {
     $this->nRows = IntegerHelper::toNatural($this->nRows);
     if (!empty($this->nRows) && $this->nRows > 1) {
         // то генерируем textarea
         $szTemplate = '<textarea rows="%d" name="%s" style="%s">%s</textarea>';
         $szResult = sprintf($szTemplate, $this->nRows, $this->szName, $this->szStyle, $this->szContent);
         return $szResult;
     }
     $szTemplate = '<input type="text" name="%s" value="%s" style="%s"/>';
     $szResult = sprintf($szTemplate, $this->szName, $this->szContent, $this->szStyle);
     return $szResult;
 }
Exemplo n.º 8
0
 public static function export($parentId = 0)
 {
     $parentId = IntegerHelper::toNatural($parentId);
     $result = array();
     $data = DBSimple::select(ACL_TABLE, "parentId = '{$parentId}'", '`name` ASC');
     foreach ($data as $row) {
         $children = self::export($row['id']);
         $add = array('id' => $row['id'], 'name' => $row['name'], 'title' => $row['title'], 'fullPath' => $row['fullPath']);
         if (!empty($children)) {
             $add['children'] = $children;
         }
         $result[] = $add;
     }
     return $result;
 }
Exemplo n.º 9
0
 /**
  * Возвращает по ID его предка
  */
 public static function createById($nId)
 {
     $nId = IntegerHelper::toNatural($nId);
     //
     $sql = 'SELECT * FROM `%s` WHERE `id`="%d"';
     $sql = sprintf($sql, SYSTEMREGISTER_TABLE, $nId);
     //
     $aResult = DB::get($sql);
     if (empty($aResult)) {
         throw new SystemRegisterException('Key with id="' . $nId . '" not found');
     }
     // Нашли корневой элемент
     if ($aResult['parent'] == 0) {
         $result = new SystemRegister($aResult['name']);
     } else {
         $result = self::createById($aResult['parent'])->get($aResult['name']);
     }
     return $result;
 }
Exemplo n.º 10
0
    /**
     * Осуществляет сортировку по определенному полю у конкретного документа
     */
    public static function sortByField($nId, $szDocumentName, $szFieldName, $bAsc = true)
    {
        //
        $nId = IntegerHelper::toNatural($nId);
        $szDocumentName = \Faid\DB::escape($szDocumentName);
        $szFieldName = \Faid\DB::escape($szFieldName);
        $bAsc = intval($bAsc);
        //
        // Получаем всех детей элемента, которые имеют указанный документ в кач. имени
        //
        $szTable = call_user_func([$szDocumentName, 'getTableName']);
        $sql = <<<SQL
\tSELECT `sitemap`.id,`sitemap`.document_id
\tFROM `%s` as `sitemap` 
\tINNER JOIN `%s` as `document` 
\tON `sitemap`.`parent` = %d and `sitemap`.document_id = `document`.id and `sitemap`.document_name = "%s" 
\tORDER BY `document`.%s %s
SQL;
        $sql = sprintf($sql, SITEMAP_TABLE, $szTable, $nId, $szDocumentName, $szFieldName, $bAsc ? ' ASC' : ' DESC');
        $aDocumentsData = DB::query($sql);
        // Получаем всех остальных детей
        $sql = 'SELECT * FROM `%s` WHERE `parent`="%d" and STRCMP(`document_name`,"%s") <> 0 ORDER by `order`';
        $sql = sprintf($sql, SITEMAP_TABLE, $nId, $szDocumentName);
        $aOtherData = DB::query($sql);
        // Выстраиваем детей совмещаем массивы, неотсортированные элементы остаются на своих местах
        $aResult = array();
        $nOrder = 0;
        while (sizeof($aDocumentsData) > 0 || sizeof($aOtherData) > 0) {
            if (!empty($aOtherData) && $aOtherData[0]['order'] == $nOrder) {
                $aElement = array_shift($aOtherData);
                $aResult[] = $aElement['id'];
            } else {
                //
                $aElement = array_shift($aDocumentsData);
                $aResult[] = $aElement['id'];
            }
            $nOrder++;
        }
        //
        Sitemap::manualOrder($nId, $aResult);
    }
Exemplo n.º 11
0
 public static function deleteAliasById($id, $aliasId)
 {
     DBSimple::delete(SITEMAP_HISTORY_TABLE, ['page_id' => IntegerHelper::toNatural($id), 'id' => IntegerHelper::toNatural($aliasId)]);
 }
Exemplo n.º 12
0
 /**
  * Устанавливает sitemap-индекс в бд
  * @param int $sitemapId
  */
 public function setupSitemapLink($sitemapId)
 {
     $this->sitemapId = IntegerHelper::toNatural($sitemapId);
     $this->store();
 }
Exemplo n.º 13
0
 /**
  *   -------------------------------------------------------------------------------------------
  *   Вызывается если передан параметр parent, тогда изменяем внутреннее значение parent и
  *   изменяем заголовок страниц, дополняем хлебные крошки страницы
  * @return
  *   -------------------------------------------------------------------------------------------
  */
 public function processParent($id, $page = 0)
 {
     try {
         $id = IntegerHelper::toNatural($id);
         $aInfo = Sitemap_Sample::get($id);
         $aParent = Sitemap_CMS::getParents($aInfo['id']);
         $this->szTitle = $aInfo['name'];
         $this->aBegin = Sitemap_CMS::selectBegin($aParent, $aInfo['name']);
         $this->nParent = intval($id);
         $this->main($page);
     } catch (Exception $e) {
         CMSLog::addMessage('sitemap-data-list', $e);
         $this->addError('Указанная страница не найдена');
         $this->jump(\Extasy\CMS::getDashboardWWWRoot() . 'sitemap/');
     }
 }
Exemplo n.º 14
0
 /**
  * Создает документ 
  * @param $document string имя документа
  * @param $place int индекс документ
  */
 public function add($document, $place)
 {
     $place = IntegerHelper::toNatural($place);
     //
     try {
         $validator = new \Extasy\Validators\IsModelClassNameValidator($document);
         if (!$validator->isValid()) {
             throw new ForbiddenException('Not a model');
         }
         $model = new $document();
         $model->createEmptyDocument($place);
     } catch (Exception $e) {
         die($e);
         throw $e;
     }
     $this->jump(\Extasy\CMS::getDashboardWWWRoot() . 'sitemap/edit.php?id=' . $model->getSitemapId());
 }
Exemplo n.º 15
0
 /**
  * Test RandomInteger random operator
  */
 public function testInteger()
 {
     IntegerHelper::setArgs(['min' => 0, 'max' => 1]);
     $this->_distributionTester('IntegerHelper::execute', [0 => 1, 1 => 1]);
     IntegerHelper::setArgs(['min' => 5, 'max' => 7]);
     $this->_distributionTester('IntegerHelper::execute', [5 => 1, 6 => 1, 7 => 1]);
     IntegerHelper::setArgs(['min' => 2, 'max' => 2]);
     $this->_distributionTester('IntegerHelper::execute', [2 => 1]);
 }
Exemplo n.º 16
0
 /**
  * Проверяет что урл доступен
  */
 protected static function checkUrlAvailable($sitemapId, $parentId, $urlKey)
 {
     $sitemapId = IntegerHelper::toNatural($sitemapId);
     $parentId = IntegerHelper::toNatural($parentId);
     $urlKey = \Faid\DB::escape($urlKey);
     // Получаем все документы с указанным url_key и parent
     $sql = 'select * from `%s` where parent = "%d" and `url_key`="%s" ';
     $sql = sprintf($sql, SITEMAP_TABLE, $parentId, $urlKey);
     $data = DB::query($sql);
     // Если их 0, то всё ок
     if (sizeof($data) == 0) {
         return;
     }
     // Если их больше 1
     if (sizeof($data) > 1) {
         // бросаем исключение
         $message = 'Sitemap tree conflict in parent_id=%d and url_key=%s ';
         $message = sprintf($message, $parentId, $urlKey);
         throw new SiteMapException($message);
     }
     // Если одна, то сравниваем индексы
     $data = $data[0];
     if ($data['id'] != $sitemapId) {
         // не совпадают
         // бросаем исключение
         $message = 'Sitemap tree conflict for sitemap_id=%d in parent_id=%d and url_key=%s url already used by sitemap_id="%d"';
         $message = sprintf($message, $sitemapId, $parentId, $urlKey, $data['id']);
         throw new SiteMapException($message);
     }
 }
Exemplo n.º 17
0
 /**
  * Сохраняет обновленные данные об SitemapXML
  * @param int $id индекс в карте sitemap
  */
 protected static function updateSitemapXMLFromPost($id)
 {
     $id = IntegerHelper::toNatural($id);
     $bFound = !empty($_POST['sitemap_xml']) && !empty($_POST['sitemap_xml']['priority']) && !empty($_POST['sitemap_xml']['change']);
     if ($bFound) {
         SitemapXML::update($id, $_POST['sitemap_xml']['priority'], $_POST['sitemap_xml']['change']);
     }
 }