├── .bitrix-cli ├── README.md ├── bitrix ├── bitrix-component.php ├── bitrix-db.php ├── bitrix-element.php ├── bitrix-error.php ├── bitrix-file.php ├── bitrix-iblock.php ├── bitrix-option.php ├── bitrix-section.php └── lib ├── BitrixCMS.php ├── BitrixCli.php ├── DataView.php ├── Exception.php ├── cli-cms.php └── index.php /.bitrix-cli: -------------------------------------------------------------------------------- 1 | # Файл конфигурации bitrix-cli 2 | # Здесь определяются конфигурация по-умолчанию. 3 | # Этот файл необходимо скопировать в домашний каталог и отредактировать. 4 | # Все переменные имеют префикс "_BX_" и могут быть перезаписаны через переменные окружения (с префиксом "BX_"). 5 | # Для активации необходимо раскомментировать необходимые строки. 6 | # Указанные здесь параметры имеют более высокий приоритет, чем значения по-умолчанию, но меньший, чем переменные окружения. 7 | 8 | # Путь к PHP. Значение по-умолчанию: `which php` 9 | # _BX_PHP=/usr/bin/php 10 | 11 | # Язык сайта (Битрикс поддерживает многоязычность, устанавливая константу `LANGUAGE_ID`) 12 | # _BX_LANGUAGE_ID=ru 13 | 14 | # Уровень ошибок. Переопределяет установленный в Битриксе уровень ошибок в прологе `/prolog_before.php` через `error_reporting()`. 15 | # Должно быть корректная конструкция PHP, так как она проходит через `eval()`. 16 | # _BX_ERR_REP='E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED' 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Описание 2 | 3 | Bitrix CLI - набор инструментов командной строки для администрирования Bitrix. Полная переработка [этого инструмента](https://github.com/dbfun/tools/blob/master/bitrix). 4 | 5 | В основе - [философия unix](https://ru.wikipedia.org/wiki/%D0%A4%D0%B8%D0%BB%D0%BE%D1%81%D0%BE%D1%84%D0%B8%D1%8F_UNIX). 6 | 7 | Параметры передаются через STDIN или параметры, результат выводится в STDOUT, а ошибки - в STDERR. 8 | 9 | Для запуска необходимо наличие PHP командной строки (пакет типа `php-cli`). Возможно указать произвольный интерпретатор PHP. 10 | 11 | # Конфигурация 12 | 13 | Конфигурация определяется через файл `~/.bitrix-cli` (для чего необходимо скопировать этот файл в домашний каталог) и переменные окружения. Если ничего не задано, используются умолчания. 14 | 15 | Приоритет: окружение > файл конфигурации > умолчания. 16 | 17 | Например, так можно определить путь до PHP через окружение: 18 | 19 | ``` 20 | export BX_PHP="/usr/bin/php7" 21 | ``` 22 | 23 | Если не установлено, используется значение `_BX_PHP` из `~/.bitrix-cli`. 24 | 25 | Если ничего не передавать - используется PHP по-умолчанию (`which php`). 26 | 27 | Возможно определить следующее: 28 | 29 | * путь к PHP 30 | * язык сайта 31 | * уровень ошибок 32 | 33 | # Составные части программы 34 | 35 | * `bitrix test` - самотестирование: какая версия PHP будет вызвана, какие параметры будут переданы в PHP 36 | * `bitrix element`, `bitrix section`, `bitrix iblock` - работа с инфоблоками: поиск, вывод содержимого, свойств инфоблока 37 | * `bitrix component` - компоненты: поиск в файле 38 | * `bitrix error` - вывод сообщений об ошибках 39 | * `bitrix event` - события: поиск, вывод в различных форматах 40 | * `bitrix user` - пользователи: поиск, вывод информации 41 | * `bitrix file` - файлы: поиск, вывод информации и содержимого файла 42 | * `bitrix option` - опции из БД 43 | * `bitrix db` - параметры подключения к БД 44 | * `bitrix php` - запуск сценария PHP с подключенным прологом (удобно для вывода переменных) 45 | 46 | Обычно необходимо передать ID элемента через `--ID (число)` или `-i (число)` и указать формат вывода через `--view`, `--format`, `-v` или `-f` (это все алиасы). 47 | 48 | Сейчас нельзя использовать plain-параметры, например `bitrix component index.php`. Возможно, следует воспользоваться https://github.com/pwfisher/CommandLine.php 49 | 50 | # Использование 51 | 52 | ## Выходной формат 53 | 54 | Формат вывода задается через `--view`, `--format`, `-v` или `-f` (это все алиасы). По-умолчанию используется `var_dump`. 55 | 56 | * `var_dump`, `var_export` - используется соответствующая функция PHP 57 | * `json` - в формате JSON `json_encode()` 58 | * `id` - выводятся только id, которые были найдены по условию 59 | * в удобном для чтения с экрана виде: `iblock`, `component`, `db`, `file`, `letter` (для событий) 60 | 61 | ## Получение элементов инфоблока 62 | 63 | ``` 64 | # Получение одного элемента 65 | bitrix element -i1000 66 | # Получение нескольких элементов 67 | bitrix element -i1000 -i1001 --ID 1002 --ID 1003 68 | # Так можно отсеять элементы, которых нет в базе данных 69 | bitrix element -i1000 -i1001 -i1003 -f id 70 | # Получение нескольких элементов, переданных через STDIN 71 | echo -e "1000\n1001" | bitrix element 72 | ``` 73 | 74 | ## Получение списка компонентов в файле 75 | 76 | ``` 77 | # явное указание файла 78 | bitrix component -x index.php 79 | # если файл не указывать, будет использован index.php 80 | bitrix component 81 | ``` 82 | 83 | ## Получение файла 84 | 85 | ``` 86 | # Получение информации о файле 87 | bitrix file -i1000 88 | # Сохранение содержимого файла 89 | bitrix file -i1000 -f src > file.jpg 90 | ``` 91 | 92 | ## Получение информации о пользователе 93 | 94 | ``` 95 | bitrix user --group 1 | bitrix user --modify active=0 96 | ``` 97 | 98 | 99 | ## Получение информации о последних ошибках 100 | 101 | ``` 102 | bitrix error 103 | ``` 104 | -------------------------------------------------------------------------------- /bitrix: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Входная точка во все исполняемые файлы 4 | # Цели: 5 | # Выбор интерпретатора PHP 6 | # Управление конфигурацией 7 | # Запуск программ (не все подпрограммы работают на PHP) 8 | 9 | 10 | # Файл настроек 11 | if [[ -e ~/.bitrix-cli ]]; then 12 | source ~/.bitrix-cli 13 | fi 14 | 15 | # Путь к PHP определяется приоритетом: 16 | # 1. Передан через окружение, например, `export BX_PHP='/usr/bin/php'` 17 | # 2. Определен в конфигурации _BX_PHP 18 | # 3. PHP, вызываемый по-умолчанию 19 | # @see README.md 20 | 21 | # Коды ошибок @see http://www.tldp.org/LDP/abs/html/exitcodes.html 22 | # @see https://stackoverflow.com/questions/1101957/are-there-any-standard-exit-status-codes-in-linux 23 | 24 | if [[ ! -z "$BX_PHP" ]]; then 25 | PHP="$BX_PHP" 26 | elif [[ ! -z "$_BX_PHP" ]]; then 27 | PHP="$_BX_PHP" 28 | else 29 | PHP=`which php` 30 | if [[ "$?" != "0" ]]; then 31 | echo "PHP not found" 32 | exit 127 33 | fi 34 | fi 35 | 36 | # LANGUAGE_ID Битрикса, так как LANGUAGE_ID привязан к переменным веб-сервера, а их нет 37 | 38 | if [[ ! -z "$BX_LANGUAGE_ID" ]]; then 39 | LANGUAGE_ID="$BX_LANGUAGE_ID" 40 | elif [[ ! -z "$_BX_LANGUAGE_ID" ]]; then 41 | LANGUAGE_ID="$_BX_LANGUAGE_ID" 42 | else 43 | LANGUAGE_ID=ru 44 | fi 45 | 46 | # Уровень вывода ошибок 47 | 48 | if [[ ! -z "$BX_ERR_REP" ]]; then 49 | ERR_REP="$BX_ERR_REP" 50 | elif [[ ! -z "$_BX_ERR_REP" ]]; then 51 | ERR_REP="$_BX_ERR_REP" 52 | else 53 | ERR_REP='E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED' 54 | fi 55 | 56 | 57 | # Параметры, которые будут переданы в исполняемые файлы 58 | export BX_ENV_LANGUAGE_ID=$LANGUAGE_ID 59 | export BX_ENV_ERR_REP=$ERR_REP 60 | 61 | BX_PHP_PATH="$(readlink -f "$0" | xargs dirname)" 62 | 63 | case $1 in 64 | # самотестирование: какая версия PHP будет вызвана, какие параметры будут переданы в PHP 65 | test) 66 | echo -e "PHP: \t\t $PHP" 67 | echo -e "LANGUAGE_ID: \t $LANGUAGE_ID" 68 | echo -e "ERR_REP: \t $ERR_REP" 69 | # $PHP -v 70 | ;; 71 | # элементы инфоблока 72 | element) 73 | # передаем все аргументы, кроме первого (первый - это текущий файл) 74 | $PHP $BX_PHP_PATH/bitrix-element.php "${@:2}" 75 | ;; 76 | # разделы инфоблока 77 | section) 78 | $PHP $BX_PHP_PATH/bitrix-section.php "${@:2}" 79 | ;; 80 | # инфоблоки 81 | iblock) 82 | $PHP $BX_PHP_PATH/bitrix-iblock.php "${@:2}" 83 | ;; 84 | # компоненты 85 | component) 86 | $PHP $BX_PHP_PATH/bitrix-component.php "${@:2}" 87 | ;; 88 | # ошибки 89 | error) 90 | $PHP $BX_PHP_PATH/bitrix-error.php "${@:2}" 91 | ;; 92 | # события 93 | event) 94 | $PHP $BX_PHP_PATH/bitrix-event.php "${@:2}" 95 | ;; 96 | # пользователи 97 | user) 98 | $PHP $BX_PHP_PATH/bitrix-user.php "${@:2}" 99 | ;; 100 | # файлы 101 | file) 102 | $PHP $BX_PHP_PATH/bitrix-file.php "${@:2}" 103 | ;; 104 | # параметры 105 | option) 106 | $PHP $BX_PHP_PATH/bitrix-option.php "${@:2}" 107 | ;; 108 | # базы данных 109 | db) 110 | $PHP $BX_PHP_PATH/bitrix-db.php "${@:2}" 111 | ;; 112 | *) 113 | echo 'Command not found' 114 | exit 64 115 | esac 116 | -------------------------------------------------------------------------------- /bitrix-component.php: -------------------------------------------------------------------------------- 1 | array(), 18 | 'val' // со значением 19 | => array('x' => 'file', 'v' => 'view', 'f' => 'format'), 20 | 'optionVal' // с необязательным значением 21 | => array(), 22 | ) 23 | ; 24 | 25 | public function __construct($BitrixCMS) { 26 | parent::__construct($BitrixCMS); 27 | } 28 | 29 | public function run() { 30 | try { 31 | $this->getParms(); 32 | $this->outputElements(); 33 | } catch (Exception $e) { 34 | $this->error($e); 35 | } 36 | } 37 | 38 | protected function getParms() { 39 | $params = $this->getCliParms(); 40 | 41 | if(isset($params['x'])) { 42 | $this->files = array_merge($this->files, (array)$params['x']); 43 | } 44 | 45 | if(isset($params['file'])) { 46 | $this->files = array_merge($this->files, (array)$params['file']); 47 | } 48 | 49 | $files = $this->getStdinStrParms(); 50 | $this->files = array_merge($this->files, $files); 51 | 52 | if(count($this->files) == 0) { 53 | try { 54 | $file = getcwd() . '/index.php'; 55 | if(!file_exists($file)) throw new Exception('No files', 1); 56 | $this->files = [$file]; 57 | } catch (Exception $e) { 58 | 59 | } 60 | 61 | 62 | } 63 | } 64 | 65 | protected $viewFormat = 'component'; 66 | protected function outputElements() { 67 | $view = $this->getViewFormat(); 68 | foreach($this->files as $file) { 69 | $this->getFile($file); 70 | if(isset($this->item)) { 71 | $DataView = new DataView($this->item); 72 | $DataView->view($view); 73 | } 74 | } 75 | } 76 | 77 | protected function getFile($file) { 78 | unset($this->item); 79 | if(!$file) { 80 | $this->warning("File not exists: " . $file); 81 | } 82 | 83 | try { 84 | if(!file_exists($file)) throw new Exception("File not exists: " . $file, 1); 85 | } catch (Exception $e) { 86 | $_file = rtrim($file, '/') . '/index.php'; 87 | if(!file_exists($_file)) { 88 | $this->warning("File not exists: " . $file); 89 | return; 90 | } 91 | $file = $_file; 92 | } 93 | 94 | $fileContent = file_get_contents($file); 95 | if(preg_match_all('~\$APPLICATION\s*->\s*IncludeComponent\s*\(\s*["|\'](.*?)["|\']~i', $fileContent, $m)) { 96 | $this->item = array('file' => $file, 'component' => $m[1]); 97 | } else { 98 | $this->warning('No "$APPLICATION->IncludeComponent" founded: ' . $file); 99 | } 100 | 101 | } 102 | 103 | } 104 | 105 | $OptionCli = new OptionCli($BitrixCMS); 106 | $OptionCli->run(); 107 | -------------------------------------------------------------------------------- /bitrix-db.php: -------------------------------------------------------------------------------- 1 | array(), 17 | 'val' // со значением 18 | => array(), 19 | 'optionVal' // с необязательным значением 20 | => array(), 21 | ) 22 | ; 23 | 24 | public function __construct($BitrixCMS) { 25 | parent::__construct($BitrixCMS); 26 | } 27 | 28 | public function run() { 29 | try { 30 | $this->outputElements(); 31 | } catch (Exception $e) { 32 | $this->error($e); 33 | } 34 | } 35 | 36 | protected function outputElements() { 37 | $config = $this->BitrixCMS->getConfig(); 38 | $connection =& $config['connections']['value']['default']; 39 | if(!isset($connection) || !$connection) throw new Exception("Empty settings: connections"); 40 | 41 | $DataView = new DataView($connection); 42 | $DataView->view('db'); 43 | } 44 | 45 | } 46 | 47 | $DbCli = new DbCli($BitrixCMS); 48 | $DbCli->run(); 49 | -------------------------------------------------------------------------------- /bitrix-element.php: -------------------------------------------------------------------------------- 1 | array(), 18 | 'val' // со значением 19 | => array('i' => 'ID', 'v' => 'view', 'f' => 'format'), 20 | 'optionVal' // с необязательным значением 21 | => array(), 22 | ) 23 | ; 24 | 25 | public function __construct($BitrixCMS) { 26 | if(!\CModule::IncludeModule('iblock')) throw new Exception('Can not include iblock'); 27 | parent::__construct($BitrixCMS); 28 | } 29 | 30 | public function run() { 31 | try { 32 | $this->getParms(); 33 | $this->outputElements(); 34 | } catch (Exception $e) { 35 | $this->error($e); 36 | } 37 | } 38 | 39 | protected function getParms() { 40 | $ids = $this->getCliIdParms(); 41 | $this->ids = array_merge($this->ids, $ids); 42 | 43 | $ids = $this->getStdinIntParms(); 44 | $this->ids = array_merge($this->ids, $ids); 45 | 46 | $this->ids = array_filter(array_unique($this->ids)); 47 | if(count($this->ids) == 0) throw new Exception('No ids', 1); 48 | } 49 | 50 | protected function outputElements() { 51 | $view = $this->getViewFormat(); 52 | foreach($this->ids as $id) { 53 | $this->getElement($id); 54 | if(isset($this->item)) { 55 | $DataView = new DataView($this->item); 56 | $DataView->view($view); 57 | if($this->isHistory) { 58 | $lastId = \CIBlockElement::WF_GetLast($id); 59 | $this->warning(sprintf('Element has history: %d, CIBlockElement::WF_GetLast(): %d' . $id, $lastId)); 60 | } 61 | } 62 | } 63 | } 64 | 65 | protected function getElement($id) { 66 | unset($this->item); 67 | $this->isHistory = false; 68 | 69 | $arSort = array('SORT' => 'ASC'); 70 | $arSelect = array('*'); 71 | $arNavStartParams = false; 72 | 73 | $arFilter = array('ID' => $id); 74 | $rs = \CIBlockElement::GetList($arSort, $arFilter, false, $arNavStartParams, $arSelect); 75 | if($rs->SelectedRowsCount() == 0) { 76 | $this->isHistory = true; 77 | $arFilter['SHOW_NEW'] = 'Y'; 78 | $rs = \CIBlockElement::GetList($arSort, $arFilter, false, $arNavStartParams, $arSelect); 79 | } 80 | if($rs->SelectedRowsCount() == 0) { 81 | $this->warning('Can not find element with id: ' . $id); 82 | } else { 83 | $this->item = $rs->Fetch(); 84 | } 85 | } 86 | 87 | } 88 | 89 | $ElementCli = new ElementCli($BitrixCMS); 90 | $ElementCli->run(); 91 | -------------------------------------------------------------------------------- /bitrix-error.php: -------------------------------------------------------------------------------- 1 | array('f' => 'file'), 18 | 'val' // со значением 19 | => array('l' => 'limit'), 20 | 'optionVal' // с необязательным значением 21 | => array(), 22 | ) 23 | ; 24 | 25 | public function __construct($BitrixCMS) { 26 | parent::__construct($BitrixCMS); 27 | } 28 | 29 | public function run() { 30 | try { 31 | $this->getParms(); 32 | $this->outputLog(); 33 | } catch (Exception $e) { 34 | $this->error($e); 35 | } 36 | } 37 | 38 | protected function getParms() { 39 | $params = $this->getCliParms(); 40 | 41 | if(isset($params['l'])) { 42 | $this->limit = $params['l']; 43 | } 44 | 45 | if(isset($params['limit'])) { 46 | $this->limit = $params['limit']; 47 | } 48 | 49 | if(isset($params['f'])) { 50 | $this->isShowLogFileName = true; 51 | } 52 | 53 | if(isset($params['file'])) { 54 | $this->isShowLogFileName = true; 55 | } 56 | } 57 | 58 | protected function outputLog() { 59 | $config = $this->BitrixCMS->getConfig(); 60 | 61 | $logFile =& $config['exception_handling']['value']['log']['settings']['file']; 62 | if(!isset($logFile) || !$logFile) throw new Exception("Empty settings: log file"); 63 | 64 | if($this->isShowLogFileName) { 65 | echo $logFile . PHP_EOL; 66 | } 67 | 68 | $cmd = sprintf('tail -n %d %s', $this->limit, escapeshellarg($logFile)); 69 | echo shell_exec($cmd); 70 | die(); 71 | } 72 | 73 | } 74 | 75 | $ErrorCli = new ErrorCli($BitrixCMS); 76 | $ErrorCli->run(); 77 | -------------------------------------------------------------------------------- /bitrix-file.php: -------------------------------------------------------------------------------- 1 | array(), 18 | 'val' // со значением 19 | => array('i' => 'ID', 'v' => 'view', 'f' => 'format'), 20 | 'optionVal' // с необязательным значением 21 | => array(), 22 | ) 23 | ; 24 | 25 | public function __construct($BitrixCMS) { 26 | parent::__construct($BitrixCMS); 27 | } 28 | 29 | public function run() { 30 | try { 31 | $this->getParms(); 32 | $this->outputElements(); 33 | } catch (Exception $e) { 34 | $this->error($e); 35 | } 36 | } 37 | 38 | protected function getParms() { 39 | $ids = $this->getCliIdParms(); 40 | $this->ids = array_merge($this->ids, $ids); 41 | 42 | $ids = $this->getStdinIntParms(); 43 | $this->ids = array_merge($this->ids, $ids); 44 | 45 | $this->ids = array_filter(array_unique($this->ids)); 46 | if(count($this->ids) == 0) throw new Exception('No ids', 1); 47 | } 48 | 49 | protected $viewFormat = 'file'; 50 | protected function outputElements() { 51 | $view = $this->getViewFormat(); 52 | foreach($this->ids as $id) { 53 | $this->getFile($id); 54 | if(isset($this->item)) { 55 | $DataView = new DataView($this->item); 56 | // TODO переделать на Service Locator 57 | $DataView->view($view, $this->BitrixCMS); 58 | } 59 | } 60 | } 61 | 62 | protected function getFile($id) { 63 | $this->item = \CFile::GetFileArray($id); 64 | if($this->item === false) { 65 | $this->warning('Can not find file with id: ' . $id); 66 | unset($this->item); 67 | } 68 | } 69 | 70 | } 71 | 72 | $FileCli = new FileCli($BitrixCMS); 73 | $FileCli->run(); 74 | -------------------------------------------------------------------------------- /bitrix-iblock.php: -------------------------------------------------------------------------------- 1 | array(), 18 | 'val' // со значением 19 | => array('i' => 'ID', 'v' => 'view', 'f' => 'format'), 20 | 'optionVal' // с необязательным значением 21 | => array(), 22 | ) 23 | ; 24 | 25 | public function __construct($BitrixCMS) { 26 | if(!\CModule::IncludeModule('iblock')) throw new Exception('Can not include iblock'); 27 | parent::__construct($BitrixCMS); 28 | } 29 | 30 | public function run() { 31 | try { 32 | $this->getParms(); 33 | $this->outputElements(); 34 | } catch (Exception $e) { 35 | $this->error($e); 36 | } 37 | } 38 | 39 | protected function getParms() { 40 | $ids = $this->getCliIdParms(); 41 | $this->ids = array_merge($this->ids, $ids); 42 | 43 | $ids = $this->getStdinIntParms(); 44 | $this->ids = array_merge($this->ids, $ids); 45 | 46 | $this->ids = array_filter(array_unique($this->ids)); 47 | if(count($this->ids) == 0) throw new Exception('No ids', 1); 48 | } 49 | 50 | protected $viewFormat = 'iblock'; 51 | protected function outputElements() { 52 | $view = $this->getViewFormat(); 53 | foreach($this->ids as $id) { 54 | $this->getIblock($id); 55 | if(isset($this->item)) { 56 | $DataView = new DataView($this->item); 57 | $DataView->view($view); 58 | } 59 | } 60 | } 61 | 62 | protected function getIblock($id) { 63 | unset($this->item); 64 | 65 | $arSort = array('SORT' => 'ASC'); 66 | 67 | $arFilter = array('id' => $id); 68 | $rs = \CIBlock::GetList($arSort, $arFilter, $bIncCnt = true); 69 | if($rs->SelectedRowsCount() == 0) { 70 | $this->warning('Can not find iblock by ID: ' . $id); 71 | } else { 72 | $this->item = $rs->Fetch(); 73 | } 74 | } 75 | 76 | } 77 | 78 | $SectionCli = new SectionCli($BitrixCMS); 79 | $SectionCli->run(); 80 | -------------------------------------------------------------------------------- /bitrix-option.php: -------------------------------------------------------------------------------- 1 | array(), 18 | 'val' // со значением 19 | => array('o' => 'option', 'v' => 'view', 'f' => 'format'), 20 | 'optionVal' // с необязательным значением 21 | => array(), 22 | ) 23 | ; 24 | 25 | public function __construct($BitrixCMS) { 26 | die('TODO'); // передача модуля и опции 27 | parent::__construct($BitrixCMS); 28 | } 29 | 30 | public function run() { 31 | try { 32 | $this->getParms(); 33 | $this->outputElements(); 34 | } catch (Exception $e) { 35 | $this->error($e); 36 | } 37 | } 38 | 39 | protected function getParms() { 40 | $params = $this->getCliParms(); 41 | 42 | if(isset($params['o'])) { 43 | $this->options = array_merge($this->options, (array)$params['o']); 44 | } 45 | 46 | if(isset($params['option'])) { 47 | $this->options = array_merge($this->options, (array)$params['option']); 48 | } 49 | 50 | $options = $this->getStdinStrParms(); 51 | $this->options = array_merge($this->options, $options); 52 | 53 | if(count($this->options) == 0) throw new Exception('No options', 1); 54 | } 55 | 56 | protected $viewFormat = 'option'; 57 | protected function outputElements() { 58 | $view = $this->getViewFormat(); 59 | foreach($this->options as $opt) { 60 | $this->getOpt($opt); 61 | if(isset($this->item)) { 62 | $DataView = new DataView($this->item); 63 | $DataView->view($view); 64 | } 65 | } 66 | } 67 | 68 | // TODO 69 | protected function getOpt($name) { 70 | $this->item = \COption::GetOptionString($moduleName, $name, ''); 71 | } 72 | 73 | } 74 | 75 | $OptionCli = new OptionCli($BitrixCMS); 76 | $OptionCli->run(); 77 | -------------------------------------------------------------------------------- /bitrix-section.php: -------------------------------------------------------------------------------- 1 | array(), 18 | 'val' // со значением 19 | => array('i' => 'ID', 'v' => 'view', 'f' => 'format'), 20 | 'optionVal' // с необязательным значением 21 | => array(), 22 | ) 23 | ; 24 | 25 | public function __construct($BitrixCMS) { 26 | if(!\CModule::IncludeModule('iblock')) throw new Exception('Can not include iblock'); 27 | parent::__construct($BitrixCMS); 28 | } 29 | 30 | public function run() { 31 | try { 32 | $this->getParms(); 33 | $this->outputElements(); 34 | } catch (Exception $e) { 35 | $this->error($e); 36 | } 37 | } 38 | 39 | protected function getParms() { 40 | $ids = $this->getCliIdParms(); 41 | $this->ids = array_merge($this->ids, $ids); 42 | 43 | $ids = $this->getStdinIntParms(); 44 | $this->ids = array_merge($this->ids, $ids); 45 | 46 | $this->ids = array_filter(array_unique($this->ids)); 47 | if(count($this->ids) == 0) throw new Exception('No ids', 1); 48 | } 49 | 50 | protected function outputElements() { 51 | $view = $this->getViewFormat(); 52 | foreach($this->ids as $id) { 53 | $this->getSection($id); 54 | if(isset($this->item)) { 55 | $DataView = new DataView($this->item); 56 | $DataView->view($view); 57 | } 58 | } 59 | } 60 | 61 | protected function getSection($id) { 62 | unset($this->item); 63 | 64 | $arSort = array('SORT' => 'ASC'); 65 | $arSelect = array('*'); 66 | $arNavStartParams = false; 67 | 68 | $arFilter = array('id' => $id); 69 | $rs = \CIBlockSection::GetList($arSort, $arFilter, $bIncCnt = true, $arSelect, $arNavStartParams); 70 | if($rs->SelectedRowsCount() == 0) { 71 | $this->warning('Can not find section by ID: ' . $id); 72 | } else { 73 | $this->item = $rs->Fetch(); 74 | } 75 | } 76 | 77 | } 78 | 79 | $SectionCli = new SectionCli($BitrixCMS); 80 | $SectionCli->run(); 81 | -------------------------------------------------------------------------------- /lib/BitrixCMS.php: -------------------------------------------------------------------------------- 1 | dir = getcwd(); 10 | } 11 | 12 | public function getConfig() { 13 | if(isset($this->config)) return $this->config; 14 | $this->config = include($this->configFile); 15 | return $this->config; 16 | } 17 | 18 | public function init() { 19 | $this->findrootDir($this->dir); 20 | $_SERVER["DOCUMENT_ROOT"] = $this->rootDir; 21 | return $this; 22 | } 23 | 24 | public function getRootDir() { 25 | return $this->rootDir; 26 | } 27 | 28 | protected function findrootDir($dir) { 29 | if(!$dir || $dir == '/') throw new Exception("Can not find bitrix root dir"); 30 | $configFile = $dir . '/bitrix/.settings.php'; 31 | if(file_exists($configFile)) { 32 | $this->rootDir = $dir; 33 | $this->configFile = $configFile; 34 | chdir($this->rootDir); 35 | return; 36 | } 37 | return $this->findrootDir(dirname($dir)); 38 | } 39 | 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /lib/BitrixCli.php: -------------------------------------------------------------------------------- 1 | BitrixCMS = $BitrixCMS; 10 | $this->_getCliParms(); 11 | $this->_getViewFormat(); 12 | } 13 | 14 | // показ предупреждения без прерывания выполнения 15 | protected function warning($msg) { 16 | fwrite(STDERR, $msg . PHP_EOL); 17 | } 18 | 19 | // показ ошибки с выходом 20 | protected function error($e) { 21 | fwrite(STDERR, $e->getMessage().PHP_EOL); 22 | die($e->getCode()); 23 | } 24 | 25 | // получение всех параметров командной строки 26 | protected function getCliParms() { 27 | return $this->args; 28 | } 29 | 30 | protected $args; 31 | private static $paramsTypeSymbol = array( 32 | 'noVal' => '', 33 | 'val' => ':', 34 | 'optionVal' => '::' 35 | ); 36 | 37 | /** 38 | * получаем параметры командной строки, распарсенные с использованием static::$cliParams 39 | * 'noVal' - параметры не должны иметь значений 40 | * 'val - параметр должен иметь значение 41 | * 'optionVal' - параметр с необязательным значением 42 | */ 43 | 44 | protected function _getCliParms() { 45 | $cliParamsStrShort = ''; 46 | $cliParamsStrLong = array(); 47 | foreach(static::$cliParams as $type => $params) { 48 | if(count($params) > 0) { 49 | $symbol = self::$paramsTypeSymbol[$type]; 50 | foreach($params as $short => $long) { 51 | $cliParamsStrShort .= $short . $symbol; 52 | $cliParamsStrLong[] = $long . $symbol; 53 | } 54 | } 55 | } 56 | $this->args = getopt($cliParamsStrShort, $cliParamsStrLong); 57 | } 58 | 59 | protected function getCliIdParms() { 60 | $ids = array(); 61 | 62 | $args =& $this->args; 63 | 64 | if(isset($args['i'])) { 65 | $_ids = $this->getIntParamList((array)$args['i']); 66 | $ids = array_merge($ids, $_ids); 67 | } 68 | if(isset($args['ID'])) { 69 | $_ids = $this->getIntParamList((array)$args['ID']); 70 | $ids = array_merge($ids, $_ids); 71 | } 72 | return $ids; 73 | } 74 | 75 | protected function getStdinIntParms() { 76 | $params = $this->getStdinParms(); 77 | $ids = $this->getIntParamList($params); 78 | return $ids; 79 | } 80 | 81 | protected function getStdinStrParms() { 82 | $params = $this->getStdinParms(); 83 | $ids = $this->getStrParamList($params); 84 | return $ids; 85 | } 86 | 87 | protected function getViewFormat() { 88 | return $this->viewFormat; 89 | } 90 | 91 | protected $viewFormat = 'var_dump'; 92 | protected function _getViewFormat() { 93 | $args =& $this->args; 94 | switch (true) { 95 | case isset($args['view']): 96 | $this->viewFormat = $args['view']; 97 | break; 98 | case isset($args['format']): 99 | $this->viewFormat = $args['format']; 100 | break; 101 | case isset($args['v']): 102 | $this->viewFormat = $args['v']; 103 | break; 104 | case isset($args['f']): 105 | $this->viewFormat = $args['f']; 106 | break; 107 | } 108 | } 109 | 110 | // STD_IN 111 | protected function getStdinParms() { 112 | stream_set_blocking(STDIN, 0); 113 | $fh = fopen('php://stdin', 'r'); 114 | $params = array(); 115 | while($param = fgets($fh, 1024)) { 116 | $param = trim($param); 117 | if($param == '') continue; 118 | $params[] = $param; 119 | } 120 | fclose($fh); 121 | return $params; 122 | } 123 | 124 | protected function getIntParamList(array $list) { 125 | $ret = array(); 126 | if(count($list) > 0) foreach($list as $val) { 127 | if(is_numeric($val)) { 128 | $ret[] = (int)$val; 129 | } else { 130 | $this->warning($val . ' is not valid numeric value'); 131 | } 132 | } 133 | return $ret; 134 | } 135 | 136 | protected function getStrParamList(array $list) { 137 | $ret = array(); 138 | if(count($list) > 0) foreach($list as $val) { 139 | $ret[] = (string)$val; 140 | } 141 | return $ret; 142 | } 143 | 144 | } 145 | -------------------------------------------------------------------------------- /lib/DataView.php: -------------------------------------------------------------------------------- 1 | iconvArray(LANG_CHARSET, 'utf-8', $data); 12 | break; 13 | } 14 | $this->data = $data; 15 | } 16 | 17 | public function view($format, $BitrixCMS) { 18 | switch($format) { 19 | case 'var_dump': 20 | $this->var_dump(); 21 | break; 22 | case 'var_export': 23 | $this->var_export(); 24 | break; 25 | case 'json': 26 | $this->json(); 27 | break; 28 | case 'id': 29 | $this->id(); 30 | break; 31 | case 'letter': 32 | $this->letter(); 33 | break; 34 | case 'iblock': 35 | $this->iblock(); 36 | break; 37 | case 'file': 38 | $this->file(); 39 | break; 40 | case 'src': 41 | $this->src($BitrixCMS); 42 | break; 43 | case 'component': 44 | $this->component(); 45 | break; 46 | case 'db': 47 | $this->db(); 48 | break; 49 | default: 50 | throw new Exception("No such view format", 1); 51 | } 52 | } 53 | 54 | protected function db() { 55 | echo sprintf("mysql:dbname=%s;host=%s\nlogin: '%s'\npassword: '%s'\noptions: %s", 56 | $this->data['database'], 57 | $this->data['host'], 58 | $this->data['login'], 59 | $this->data['password'], 60 | $this->data['options'] 61 | ); 62 | echo PHP_EOL; 63 | } 64 | 65 | protected function component() { 66 | echo sprintf("%s\n%s", $this->data['file'], implode(', ', $this->data['component'])); 67 | echo PHP_EOL; 68 | } 69 | 70 | protected function iblock() { 71 | echo sprintf("[%d] %s\nACTIVE: %s\nELEMENT_CNT: %d\nLIST_PAGE_URL: %s", 72 | $this->data['ID'], $this->data['NAME'], 73 | $this->data['ACTIVE'], $this->data['ELEMENT_CNT'], $this->data['LIST_PAGE_URL'] 74 | ); 75 | echo PHP_EOL . PHP_EOL; 76 | } 77 | 78 | protected function file() { 79 | echo sprintf("[%d] %s\nFILE_NAME: %s\nFILE_SIZE: %d\nCONTENT_TYPE: %s\nTIMESTAMP_X: %s", 80 | $this->data['ID'], $this->data['SRC'], $this->data['FILE_NAME'], $this->data['FILE_SIZE'], $this->data['CONTENT_TYPE'], $this->data['TIMESTAMP_X'] 81 | ); 82 | echo PHP_EOL . PHP_EOL; 83 | } 84 | 85 | protected function src($BitrixCMS) { 86 | $file = rtrim($BitrixCMS->getRootDir(), '/') . '/' . ltrim($this->data['SRC'], '/'); 87 | if(!file_exists($file)) throw new Exception("File not exists: " . $file, 1); 88 | readfile($file); 89 | } 90 | 91 | protected function id() { 92 | echo $this->data['ID'] . PHP_EOL; 93 | } 94 | 95 | protected function letter() { 96 | echo $this->data['ID'] . ' > ' . $this->data['EVENT_NAME'].PHP_EOL; 97 | echo implode(PHP_EOL, $this->data['C_FIELDS']); 98 | echo PHP_EOL.PHP_EOL; 99 | } 100 | 101 | protected function var_dump() { 102 | var_dump($this->data); 103 | echo PHP_EOL; 104 | } 105 | 106 | protected function var_export() { 107 | var_export($this->data); 108 | echo PHP_EOL; 109 | } 110 | 111 | protected function json() { 112 | echo json_encode($this->data); 113 | echo PHP_EOL; 114 | } 115 | 116 | protected function iconvArray($charset_from, $charset_to, $arData) { 117 | $arTmp = array(); 118 | foreach($arData as $k => $_v) 119 | { 120 | if(is_array($_v)) { 121 | $v = $this->iconvArray($charset_from, $charset_to, $_v); 122 | } else { 123 | $v = iconv($charset_from, $charset_to.'//IGNORE', $_v); 124 | if(empty($v)) $v = iconv($charset_from, $charset_to.'//TRANSLIT', $_v); 125 | } 126 | $k = iconv($charset_from, $charset_to.'//IGNORE', $k); 127 | $arTmp[$k] = $v; 128 | } 129 | return $arTmp; 130 | } 131 | 132 | } 133 | -------------------------------------------------------------------------------- /lib/Exception.php: -------------------------------------------------------------------------------- 1 | init(); 16 | 17 | $LANGUAGE_ID = getenv('BX_ENV_LANGUAGE_ID'); 18 | if($LANGUAGE_ID === false) { $LANGUAGE_ID = 'ru'; } 19 | 20 | // Язык сайта 21 | 22 | define('LANGUAGE_ID', $LANGUAGE_ID); 23 | define("NO_KEEP_STATISTIC", true); 24 | define("NOT_CHECK_PERMISSIONS", true); 25 | require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php"); 26 | 27 | // Уровень ошибок 28 | 29 | $BX_ENV_ERR_REP = getenv('BX_ENV_ERR_REP'); 30 | if($BX_ENV_ERR_REP === false) { $BX_ENV_ERR_REP = 'E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED'; } 31 | $BX_ENV_ERR_REP = eval('return ' . $BX_ENV_ERR_REP . ';'); 32 | error_reporting($BX_ENV_ERR_REP); 33 | -------------------------------------------------------------------------------- /lib/index.php: -------------------------------------------------------------------------------- 1 |