In-Portal Developers Guide

This is a wiki-based Developers Guide for In-Portal Open Source CMS. The purpose of this guide is to provide advanced users, web developers and programmers with documentation on how to expand, customize and improve the functionality and the code the In-Portal software. Please consider contributing to our documentation writing effort.

K4:Environment Variable

From In-Portal Developers Guide

Jump to: navigation, search
m (1 версия)
Current revision (23:14, 27 November 2010) (view source)
 
(13 intermediate revisions not shown.)
Line 1: Line 1:
{{toc | category = Структура приложения | sortkey = 004.001}}
{{toc | category = Структура приложения | sortkey = 004.001}}
<!-- Пишите ПОСЛЕ этой строки, пожалуйста. Ничего не стирать! -->
<!-- Пишите ПОСЛЕ этой строки, пожалуйста. Ничего не стирать! -->
-
Переменная окружения представляет из себя обычную переменную из запроса к серверу с названием "<code>env</code>". Само название данной переменной задано в константе [[K4:Константы#ENV_VAR_NAME|ENV_VAR_NAME]]. Она была введена для того, чтобы реализовать возможность компактной передачи большого количества переменных между страницами сайта. В большинстве случаев в ней будет содержаться информация, при помощи которой можно будет загрузить объект из [[K4:Работа с базой данных|базы данных]] на странице (т.е. [[K4:Unit Configs#Prefix|префикс]] и <code>ID</code>), но это совсем не обязательно.
+
The Environment variable is a standard query variable called "<code>env</code>". Name of this variable is defined in [[K4:Константы#ENV_VAR_NAME|ENV_VAR_NAME]] constant. The purpose of <code>env</code> variable is to pass a large number of variables in a compact way through the website pages. In most cases <code>env</code> variable will carry the values to load the object from the [[K4:Работа с базой данных|database]] on the current page (т.е. [[K4:Unit Configs#Prefix|Prefix]] и <code>ID</code>), but usage is not limited by that.
-
Если в [[K4:Unit Configs|конфигурационном файле]] переданного [[K4:Unit Configs#Prefix|префикс]]а разрешена [[K4:Unit_Configs#AutoLoad|автоматическая загрузка]], то при первом обращении к объекту [[K4:Unit Configs#Prefix|префикс]] которого передан и при наличии его <code>ID</code> в запросе к серверу он будет автоматически загружен.
+
Note that in case if in [[K4:Unit Configs|Configuration file]] of passed the [[K4:Unit Configs#Prefix|Prefix]] is allowed [[K4:Unit_Configs#AutoLoad|auto-loading]], then at the time of first call to that object of [[K4:Unit Configs#Prefix|Prefix]] and existence of object <code>ID</code> in the <code>env</code> variable then that object will be loaded automatically.
-
== Структура ==
+
== Structure ==
-
Значение, содержащееся в переменной окружения имеет следующую структуру:
+
The value contained in the environment variable has the following structure:
  <session_id>-<template>:m<main_prefix_variables>[:<prefix[.special]>-<value1>[-<value2>...[-<valueN>]]]
  <session_id>-<template>:m<main_prefix_variables>[:<prefix[.special]>-<value1>[-<value2>...[-<valueN>]]]
-
Как видно из приведённой выше схемы в переменной окружения всегда присутствуют следующие компоненты:
+
For the above scheme, it can be seen that the environment variable is always made up of the following components:
-
* <code>session_id</code> - [[K4:UserSession#SessionKey|идентификатор сессии]] [[K4:PortalUser|пользователя]];
+
-
* <code>template</code> - путь к шаблону, результат обработки которого будет показан на экране;
+
-
* <code>main_prefix_variables</code> - ряд системных переменных, среди которых в том числе присутствуют [[K4:Theme#ThemeId|ID темы]] и [[K4:Language|ID языка]], которые будут использованы для вывода информации на странице (об этом позже).
+
-
Также в ней могут присутствовать данные неограниченного количества [[K4:Unit Configs#Prefix|префикс]]ов. Наборы данных разных [[K4:Unit Configs#Prefix|префикс]]ов друг от друга отделяются двоеточием ("<code>:</code>"). Первое значение внутри каждого набора - [[K4:Unit Configs#Prefix|префикс]] конфигурационного файла. Если необходимо, то можно указать и "<code>special</code>" следующим образом: "<code>prefix.special</code>".
+
* <code>session_id</code> - [[K4:UserSession#SessionKey|session identifier]] [[K4:PortalUser|user]];
 +
* <code>template</code> - path to the template, the rendering of which will be shown on the screen;
 +
* <code>main_prefix_variables</code> - system variables, among which are [[K4:Theme#ThemeId|theme ID]] and [[K4:Language|language ID]], which will be used to output information on the page (will be explained later).
-
Далее следует список параметров [[K4:Unit Configs#Prefix|префикс]]а, которые могут передаваться через переменную окружения, разделённых при помощи дефиса ("<code>-</code>"). Названия параметров, а также их порядок в пределах одного набора [[K4:Unit Configs#Prefix|префикс]]а задаётся в ключе [[K4:Unit Configs#QueryString|QueryString]] его [[K4:Unit Configs|конфигурационного файла]]. Например:
+
Also, it may contain data from an unlimited number of [[K4:Unit Configs#Prefix|prefix]]es. Data sets from different [[K4:Unit Configs#Prefix|prefix]]es are separated with a colon ("<code>:</code>"). The first value in each set is the [[K4:Unit Configs#Prefix|prefix]] of the configuration file. If necessary, then the "<code>special</code>" can be indicated in the following format: "<code>prefix.special</code>".
 +
 
 +
The following is a list of parameters of the [[K4:Unit Configs#Prefix|prefix]] that can be passed through the environment variable, delimited using a hyphen ("<code>-</code>"). Parameter names and their order in a single set of a [[K4:Unit Configs#Prefix|prefix]] is set in the key [[K4:Unit Configs#QueryString|QueryString]] of its Configs|configuration file]]. For example:
<source lang="php">
<source lang="php">
'QueryString' => Array(
'QueryString' => Array(
Line 26: Line 27:
</source>
</source>
-
Пиведённое выше значение ключа [[K4:Unit Configs#QueryString|QueryString]] является стандартным для большинства [[K4:Unit Configs#Prefix|префикс]]ов и поэтому будет описано ниже.
+
The above key value [[K4:Unit Configs#QueryString|QueryString]] is the standard for most [[K4:Unit Configs#Prefix|prefix]]es and therefore will be described below.
{| class="prettytable"
{| class="prettytable"
-
! название || описание
+
! Name || Description
|-
|-
-
| <code>id</code> || ID объекта (<code>Item</code>), которое может быть использовано для [[K4:Unit Configs#AutoLoad|автоматической загрузки]] объекта.
+
| <code>id</code> || Object ID (<code>Item</code>) that can be used for [[K4:Unit Configs#AutoLoad|automatic loading]] of an object.
|-
|-
-
| <code>Page</code> || Номер страницы списка объектов (<code>List</code>).
+
| <code>Page</code> || Page number of the object list (<code>List</code>).
|-
|-
-
| <code>event</code> || [[EventHandler:About|Событие]], которое требуется выполнить у данного [[K4:Unit Configs#Prefix|префикс]]а.
+
| <code>event</code> || [[EventHandler:About|Event]], that needs to be executed from a given [[K4:Unit Configs#Prefix|prefix]].
|-
|-
| <code>mode</code>
| <code>mode</code>
-
| Режим редактирования записей. Возможны 3 вида значений:
+
| Three types of values are possible:
-
* "" - данные будут редактироваться в оригинальной таблице;
+
* "" - values will be edited in the original table;
-
* "<code>t</code>" - данные будут редактироваться во временной таблице в основном окне;
+
* "<code>t</code>" - values will be edited in a temporary table in the main window;
-
* "<code>t<wid></code>" - данные будут редактироваться во временной таблице, которая была создана при открытии всплывающего окна (<code>popup</code>) с идентификатором окна (<code>window id</code>) равным "<code><wid></code>".
+
* "<code>t<wid></code>" - values will be edited in a temporary table that was created as the result of a <code>popup</code>, where the <code>window id</code> is "<code><wid></code>".
|}
|}
-
{{InfoBox|Значения данного массива чувствительны к регистру (<code>case-sensitive</code>).}}
+
{{InfoBox|The values in this array are (<code>case-sensitive</code>).}}
 +
 
 +
== Getting Data from the Environment Variable ==
 +
If the URL used to open the site contains an environment variable, then its value will automatically be processed by the system. Direct access to the value of the environment variable isn't recommended. The result of processing '''each''' of the passed [[K4:Unit Configs#Prefix|prefixes]] creates variables, e.g. "<code>'''prefix[.special]_VariableName'''</code>". One variable will be created for each '''value''' in the [[K4:Unit Configs#QueryString|QueryString]] array  of the passed [[K4:Unit Configs#Prefix|prefix]]. Variables created by this process can then be used just like any other variables passed in a request to the server (i.e. use the method <code>'''Application::GetVar'''</code>). This will be demonstrated in the below example.
 +
* Variables defined in the [[K4:Unit Configs|configuration file]]:
-
== Получение данных из переменной окружения ==
 
-
Если в ссылке, используемой для посещения сайта находиться переменная окружения, то её значение будет автоматически обработано системой. Доступ напрямую к значению переменной окружения не рекомендуется. В результате обработки '''для каждого''' из переданных [[K4:Unit Configs#Prefix|префиксов]] будут искуственно созданы переменные вида "<code>'''prefix[.special]_VariableName'''</code>". Будет создано по одной переменной для каждого '''значения''' в массиве [[K4:Unit Configs#QueryString|QueryString]] у переданного [[K4:Unit Configs#Prefix|префикс]]а. Созданные таким образом переменные можно будет в последствии использовать также, как и любые другие переменные, переданные в запросе к серверу (т.е. при помощи метода <code>'''Application::GetVar'''</code>). Это будет наглядно показано на ниже приведённом примере.
 
-
* Переменные, заданные в [[K4:Unit Configs|конфигурационном файле]]:
 
<source lang="php">
<source lang="php">
'Prefix' => 'sample-prefix',
'Prefix' => 'sample-prefix',
Line 56: Line 58:
</source>
</source>
-
* Значение переменной окружения:
+
* Environment Variable Values:
<source lang="xml">-template:m0--1--s-:sample\-prefix-15-testing</source>
<source lang="xml">-template:m0--1--s-:sample\-prefix-15-testing</source>
-
В выше приведённом примере у префикса "<code>sample-prefix</code>" в [[K4:Unit Configs|конфигурационном файле]] определены 2 переменные: "<code>sample_variable</code>" и "<code>another_variable</code>". В переменной окружения для данного префикса переданы значения этих переменных, равные "<code>15</code>" и "<code>testing</code>" соответственно. После обработки переменной окружения для данного префикса буду созданы 2 переменные:
+
There are two variables defined in the above example for the "<code>sample-prefix</code>" prefix in the [[K4:Unit Configs|configuration file]]: "<code>sample_variable</code>" and "<code>another_variable</code>". The values that are passed in the environment variable for this prefix are  "<code>15</code>" and "<code>testing</code>", respectively. Two variables will be created after processing the environment variable for this prefix:
{| class="prettytable"
{| class="prettytable"
-
! название || значение
+
! Name || Value
|-
|-
| <code>sample-prefix_sample_variable</code> || <code>15</code>
| <code>sample-prefix_sample_variable</code> || <code>15</code>
Line 67: Line 69:
| <code>sample-prefix_another_variable</code> || <code>testing</code>
| <code>sample-prefix_another_variable</code> || <code>testing</code>
|}
|}
-
{{TipBox|Переменная будет создана, даже если её значение не передано.}}
+
{{TipBox|The variable will be created even if a value isn't passed.}}
-
Получить значение любой из созданных выше переменных можно будет используя код вида:
+
The following code will allow getting the value of either of the variables created above:
{| class="prettytable"
{| class="prettytable"
-
! пример для <code>PHP</code> || пример для шаблона
+
! <code>PHP</code> Example || Template Example
|-
|-
| <source lang="php">$sample_variable = $this->Application->GetVar('sample-prefix_sample_variable');</source>
| <source lang="php">$sample_variable = $this->Application->GetVar('sample-prefix_sample_variable');</source>
| <source lang="xml">value: <inp2:m_Get name="sample-prefix_sample_variable"/></source>
| <source lang="xml">value: <inp2:m_Get name="sample-prefix_sample_variable"/></source>
|}
|}
-
{{InfoBox|Чтобы не "зашивать" значение префикса в коде его можно получить динамически используя методы <code>'''kEvent::getPrefixSpecial()'''</code> (для [[EventHandler:About|событий]]) и <code>'''TagProcessor:getPrefixSpecial()'''</code> (для [[TagProcessor:About|тэгов]]).}}
+
{{InfoBox|To avoid hard-coding the value of the prefix, it can be obtained dynamically using the following methods:<code>'''kEvent::getPrefixSpecial()'''</code> (for [[EventHandler:About|events]]) and <code>'''TagProcessor:getPrefixSpecial()'''</code> (for [[TagProcessor:About|tags]]).}}
-
== Построение ссылок ==
+
== Building Links ==
-
Т.к. переменная окружения используется только для компактной передачи данных между страницами сайта, то единственным способом в неё что-либо записать является построение ссылки. Все ссылки в K4 строятся используя метод "<code>'''Application::HREF'''</code>". Например он используется в методе <code>'''Application::Redirect'''</code>, а также в [[TagProcessor:About|тэгах]] [[TagProcessor:m_Link|m_Link]], [[TagProcessor:st_ContentBlock|st_ContentBlock]], [[TagProcessor:lang_LanguageLink|lang_LanguageLink]] и [[TagProcessor:m_FormAction|m_FormAction]]. Этот метод принимает 4 описанных ниже параметра.
+
Since the environment variable is used to compactly pass data between the pages of a site, the only way to to add something to it is by building a link. All links in K4 are built using the method "<code>'''Application::HREF'''</code>". For example, it's used in the method code>'''Application::Redirect'''</code> and in the [[TagProcessor:About|tags]] [[TagProcessor:m_Link|m_Link]], [[TagProcessor:st_ContentBlock|st_ContentBlock]], [[TagProcessor:lang_LanguageLink|lang_LanguageLink]] and [[TagProcessor:m_FormAction|m_FormAction]]. This method accepts the following four parameters.
{| class="prettytable"
{| class="prettytable"
-
! параметр || описание
+
! Parameter || Description
|-
|-
-
| {{ConfigProperty|$t|string}} || Название шаблона, ссылку на который требуется построить (напр. "<code>custom/tests/test_edit</code>"). Параметр обязательный, но если передать пустое значение, то будет использован текущий (тот, на который зашёл пользователь) шаблон.
+
| {{ConfigProperty|$t|string}} || Name of the template to which a link needs to be built (for example "<code>custom/tests/test_edit</code>"). This parameter is required, but if a blank value is passed, then the current template will be used (the one the user opened).
|-
|-
-
| {{ConfigProperty|$prefix|string}} || Данный необязательный параметр предназначен для того, чтобы можно было находясь в административной консоли построить ссылку на пользовательскую часть сайта. Для того, чтобы это сделать нужно передать в него значение "<code>_FRONT_END_</code>". {{InfoBox|На текущий момент данная функциональность не работает (см. [[Вопрос:Как принудительно указать тегу m Link строить линк на Front-End?|этот вопрос]]) и чтобы построить ссылку на пользовательскую часть сайта нужно передать "<code>index.php</code>" в качестве значения параметра [[#index_file|index_file]].}}
+
| {{ConfigProperty|$prefix|string}} || This optional parameter is available to make it possible to build a link to the front end of the site while located in the administrative console. To do this, it's value has to be passed as "<code>_FRONT_END_</code>". {{InfoBox|Currently, this functionality doesn't work (see [[Question:How to tell the m Link tag to build a link to the Front-End?|this question]]) and to build a link to the front-end, "<code>index.php</code>" has to be passed as the value of the [[#index_file|index_file]] parameter.}}
|-
|-
-
| {{ConfigProperty|$params|array}} || Набор параметров, которые следует передать в ссылку. Помимо параметров общего применения можно также передать ряд параметров специального назначения, описанных [[#Параметры специального назначения|ниже]].
+
| {{ConfigProperty|$params|array}} || This is a set of parameters that should be passed in a link. In addition to passing general application parameters, it's also possible to pass many special purpose parameters, which are described in [[#Special Purpose Parameters|below]].
|-
|-
-
| {{ConfigProperty|$index_file|string}} || Необязательное название <code>php</code> файла, который следует использовать в результирующей ссылке. По умолчанию равен "<code>index.php</code>" (для пользовательской части сайта) и "<code>admin/index.php</code>" (для административной консоли).
+
| {{ConfigProperty|$index_file|string}} || Optional name of the <code>php</code> file that should be used in the resulting link. By default, it's set to "<code>index.php</code>" (for the front-end) and "<code>admin/index.php</code>" (for the administrative console).
|}
|}
-
=== Параметры специального назначения ===
+
=== Special Purpose Parameters ===
{| class="prettytable"
{| class="prettytable"
-
| {{ConfigProperty|pass|string}} || В данном параметре передаются названия тех [[K4:Unit Configs#Prefix|префикс]]ов (через запятую), которые будут использоваться при построении значения переменной окружения в результирующей ссылке. Также можно передать значение "<code>'''all'''</code>", чтобы были использованы все [[K4:Unit Configs#Prefix|префикс]]ы из ссылки на текущую страницу сайта. Например, "<code>m,sample-prefix</code>" или "<code>all</code>". {{TipBox|Также следует отметить, что '''всегда''', когда указывается список префиксов первым из них должен быть [[K4:Unit Configs#Prefix|префикс]] "<code>m</code>".}}
+
| {{ConfigProperty|pass|string}} || In this parameter are passed the names of the [[K4:Unit Configs#Prefix|prefix]] tags (comma delimited) that will be used for building the value of the environment variable in the resulting link. It's also possible to pass the value "<code>'''all'''</code>" so that all [[K4:Unit Configs#Prefix|prefix]]es in a link are used on the page of a site. For example, "<code>m,sample-prefix</code>" or "<code>all</code>". {{TipBox|'''Always''' when writing a list of prefixes, the first one must be the [[K4:Unit Configs#Prefix|prefix]] "<code>m</code>".}}
|-
|-
| {{ConfigProperty|index_file|string}}
| {{ConfigProperty|index_file|string}}
-
| Альтернативный способ задания значения параметра "<code>index_file</code>" методу <code>Application::HREF</code> через шаблон. Например (если передать "<code>another_index.php</code>"):
+
| An alternative way to set the value of the "<code>index_file</code>" parameter for the <code>Application::HREF</code> method through the template. For example (if passing "<code>another_index.php</code>"):
<source lang="xml">
<source lang="xml">
-
http://www.sample-site.com/another_index.php?env=-template:m0--1--s- (с параметром)
+
http://www.sample-site.com/another_index.php?env=-template:m0--1--s- (with parameter)
-
http://www.sample-site.com/index.php?env=-template:m0--1--s- (без параметра)
+
http://www.sample-site.com/index.php?env=-template:m0--1--s- (without parameter)
</source>
</source>
|-
|-
| {{ConfigProperty|escape|int}}
| {{ConfigProperty|escape|int}}
-
| Если указать данный параметр, то на результирующую ссылку будет применена функция [http://php.prod.intechnic.lv/manual/en/function.addslashes.php addslashes]. Только при использовании на шаблонах вместо данного параметра следует использовать параметр "<code>'''js_escape'''</code>", т.к. он является усовершенствованной версией данного параметра и будет работать для всех тэгов. Например (если передать "<code>1</code>"):
+
| If this parameter is defined, then the [http://php.prod.intechnic.lv/manual/en/function.addslashes.php addslashes] function will be applied to the resulting link. When using in a template, use "<code>'''js_escape'''</code>" instead of this parameter because it's the latest version of this parameter and will work for all tags. For example (if passing "<code>1</code>"):
<source lang="xml">
<source lang="xml">
-
http://www.sample-site.com/index.php?env=-template:m0--1--s-:sample\\-prefix-15-testing (с параметром)
+
http://www.sample-site.com/index.php?env=-template:m0--1--s-:sample\\-prefix-15-testing (with parameter)
-
http://www.sample-site.com/index.php?env=-template:m0--1--s-:sample\-prefix-15-testing (без параметра)
+
http://www.sample-site.com/index.php?env=-template:m0--1--s-:sample\-prefix-15-testing (without parameter)
</source>
</source>
-
Обычно параметр "<code>'''js_escape'''</code>" (в шаблонах) следует использовать для построения ссылок, используемых в <code>JavaScript</code>.
+
Usually the "<code>'''js_escape'''</code>" (in templates) is used to build links that are used in <code>JavaScript</code>.
|-
|-
| {{ConfigProperty|anchor|string}}
| {{ConfigProperty|anchor|string}}
-
| Данный параметр позволяет добавить указанное в нём значение, как якорь к результирующей ссылке. Например (если передать "<code>sample_anchor</code>"):
+
| This parameter allows adding the value defined in it as an anchor in the resulting link. For example (passing "<code>sample_anchor</code>"):
<source lang="xml">
<source lang="xml">
-
http://www.sample-site.com/index.php?env=-template:m0--1--s-#sample_anchor (с параметром)
+
http://www.sample-site.com/index.php?env=-template:m0--1--s-#sample_anchor (with parameter)
-
http://www.sample-site.com/index.php?env=-template:m0--1--s- (без параметра)
+
http://www.sample-site.com/index.php?env=-template:m0--1--s- (without parameter)
</source>
</source>
|-
|-
| {{ConfigProperty|no_amp|int}}
| {{ConfigProperty|no_amp|int}}
-
| Если передать данный параметр, то все переменные, используемые в результирующей ссылке будут объединены используя символ "<code>&</code>" (совместимо с <code>JavaScript</code>). Во всех остальных случаях переменные будут объединены при помощи строки "<code>&amp;amp;</code>" (совместимо с <code>HTML</code>). Например (если передать "<code>1</code>"):
+
| If this parameter is passed, then all variables, used in the resulting link will be combined with the "<code>&</code>" symbol (compatible with <code>JavaScript</code>). In all other cases, the variables will be combined using the "<code>&amp;amp;</code>" characters (compatible with <code>HTML</code>). For example, (if passing "<code>1</code>"):
<source lang="xml">
<source lang="xml">
-
http://www.sample-site.com/index.php?env=-template:m0--1--s-&amp;sample_parameter=value1&amp;another_parameter=value2 (с параметром)
+
http://www.sample-site.com/index.php?env=-template:m0--1--s-&amp;sample_parameter=value1&amp;another_parameter=value2 (with parameter)
-
http://www.sample-site.com/index.php?env=-template:m0--1--s-&sample_parameter=value1&another_parameter=value2 (без параметра)
+
http://www.sample-site.com/index.php?env=-template:m0--1--s-&sample_parameter=value1&another_parameter=value2 (without parameter)
</source>
</source>
|}
|}
-
=== Использование переданных параметров ===
+
=== Using Passed Parameters ===
-
Сначала все переданные параметры делятся на '''3 группы''':
+
All passed parameters are divided into '''3 groups''':
-
* параметры [[#Параметры специального назначения|специального назначения]];
+
* [[#Special use parameters|Special use]] parameters]];
-
* параметры, которые будут использоваться в [[#Структура|переменной окружения]];
+
* Parameters that will be used in the [[#Структура|environment variable]];
-
* остальные параметры.
+
* All other parameters.
-
Берётся список [[K4:Unit Configs#Prefix|префикс]]ов из значения параметра [[#pass|pass]] и для каждого префикса выстраивается [[#Структура|фрагмент]] переменной окружения, который будет его представлять. В случае, если значение той или иной [[#Структура|переменной префикса]] не задано в параметрах, то берётся значение, полученное из запроса к серверу или пустая строка, если ничего передано небыло. Все параметры, которые '''были использованы''' при построении значения переменной окружения убираются из общего списка параметров (чтобы они не попали в результирующую ссылку).
+
A list of [[K4:Unit Configs#Prefix|prefix]]es is taken from the value of the [[#pass|pass]] parameter and a [[#Структура|fragment]] of the environment variable is set for each prefix that will represent it. If the value of a [[#Структура|variable's prefix]] isn't indicated in the parameter, the value received in the request to the server will be used or, if nothing was passed then a blank space will be used. Al parameters that '''were used''' in building the value of the environment variable are removed from the general list of parameters (to avoid them ending up in the resulting link).
-
Остальные, не использованные в переменной окружения параметры (кроме параметров [[#Параметры специального назначения|специального назначения]]) добавляются к результирующей ссылке используя строку "<code>&amp;amp;</code>" или "<code>&</code>" (если используется параметр специального назначения [[#no_amp|no_amp]]).
+
The rest of the parameters, having not been used in the environment variable parameter (except [[#Special purpose parameters|special purpose]] parameters), are added to the resulting link using the line "<code>&amp;amp;</code>" or "<code>&</code>" (if the special purpose parameter is used [[#no_amp|no_amp]]).
-
После выполнения всех выше описанных шагов на полученную ссылку применяются переданные параметры [[#Параметры специального назначения|специального назначения]].
+
After the completion of the all of the above steps, the [[#Special purpose parameters|special purpose]] parameters are applied to the link.
-
== Запись данных ==
+
== Recording Data ==
-
Запись значений в переменную окружения из шаблонов сводится к формированию ссылки, по которой в последствии перейдёт пользователь. Формирование ссылок внутри шаблонов производится с помощью тэга [[TagProcessor:m_Link|m_Link]]. В ниже приведённом примере продемонстрировано его использование.
+
Recording values into the environment variable from templates results in creating the link, which the user will eventually follow. Formatting links from templates is done with the [[TagProcessor:m_Link|m_Link]] tag. The below examples demonstrates its use.
-
=== Запись данных из шаблонов ===
+
=== Recording Data from a Template ===
<source lang="xml">
<source lang="xml">
<a href="<inp2:m_Link template='cart' cart_event='OnAddProduct' pass='m,cart,product'/>">Add To Cart</a>
<a href="<inp2:m_Link template='cart' cart_event='OnAddProduct' pass='m,cart,product'/>">Add To Cart</a>
</source>
</source>
-
Ниже приведено описание параметров тэга [[TagProcessor:m_Link|m_Link]], использованных в выше приведённом примере.
+
Below are descriptions of [[TagProcessor:m_Link|m_Link]] tag parameters, used in the above example.  
{| class="prettytable"
{| class="prettytable"
-
! параметр || пояснение
+
! Parameter || Explanation
|-
|-
-
| {{ConfigProperty|template|string}} || Путь к шаблону. В пользовательской части сайта это путь относительно директории с [[K4:Theme|темой]].
+
| {{ConfigProperty|template|string}} || Path to the template. On the front-end, this is the path relative to the [[K4:Theme|theme]] directory.
|-
|-
-
| {{ConfigProperty|cart_event|string}} || Название [[EventHandler:About|события]] для префикса <code>cart</code>. Указанное событие будет выполнено только в том случае, когда префикс <code>cart</code> указан в параметре <code>pass</code>.
+
| {{ConfigProperty|cart_event|string}} || The name of the [[EventHandler:About|event]] for the <code>cart</code> prefix. The indicated event will be executed only in the case where the <code>cart</code> prefix is set in the <code>pass</code> parameter.
|-
|-
-
| {{ConfigProperty|pass|string}} || Параметр указывает на то, данные каких префиксов необходимо передать в переменной окружения.
+
| {{ConfigProperty|pass|string}} || This parameter indicates the prefixes whose data must be passed in the environment variable.  
|}
|}
-
=== Запись данных из событий ===
+
=== Recording Data from an Event ===
-
После успешного выполнения каждого [[EventHandler:About|события]] происходит автоматическое перенаправление на шаблон, с которого данное событие было вызвано. Для того, чтобы в ссылке построенной для этого перенаправления присутствовали дополнительные параметры нужно использовать метод '''<code>kEvent:setRedirectParam</code>'''. В свою очередь свойство '''<code>kEvent:redirect</code>''' позволит задать альтернативный шаблон, использующийся в ссылке на перенаправление. Это будет наглядно показано на ниже приведённом примере.
+
After successfully executing each [[EventHandler:About|event]], there is an automatic redirect to the template, from which the event was called. In order for the link that was built for the redirect to contain additional parameters, the method '''<code>kEvent:setRedirectParam</code>''' must be used. '''<code>kEvent:redirect</code>''' event will allow setting an alternative template to be used in the redirect link. This is demonstrated in the below example.
<source lang="php">
<source lang="php">
Line 176: Line 178:
}
}
</source>
</source>
-
В данном примере значение переменной "<code>param_name</code>" будет доступно на шаблоне "<code>alternative_destination_template</code>". Подробнее о последующем получении значений переданных параметров написано в [[#Получение данных из переменной окружения|этой, выше описанной главе]].
+
In this example, the value of the "<code>param_name</code>" variable will be available on the "<code>alternative_destination_template</code>" template. More information on getting the values of passed parameters is written in [[#Getting data from the Environment Variable|Above Heading]].
-
== Системные переменные окружения ==
+
== System Environment Variables ==
-
Помимо данных от пользовательских [[K4:Unit Configs#Prefix|префиксов]] в переменной окружения всегда передаётся префикс "<code>m</code>" (<code>main</code>), содержащий системные переменные окружения. Конфигурационный файл от данного префикса находиться в папке "<code>core/units/general</code>" и соответственно называется "<code>general_config.php</code>" (название папки плюс "<code>_config.php</code>"). В данном конфигурационном файле используется ключ [[K4:Unit Configs#PortalStyleEnv|PortalStyleEnv]], из-за которого в результирующей переменной окружения для данного префикса не будет дефиса ("<code>-</code>") между названием префикса и значением его первой переменной (т.е. "<code>m5</code>", а не "<code>m-5</code>" как обычно). При помощи данного префикса передаются следующие переменные:
+
Apart from data from user [[K4:Unit Configs#Prefix|prefixes]], the "<code>m</code>" (<code>main</code>) prefix is always passed into the environment variable. It contains system environment variables. The prefix's configuration file is located in the "<code>core/units/general</code>" folder and is named "<code>general_config.php</code>" (name of the folder plus "<code>_config.php</code>"). There is a key ([[K4:Unit Configs#PortalStyleEnv|PortalStyleEnv]]) used in this configuration file, because of which the resulting environment variable for the prefix will not contain a dash ("<code>-</code>") between the name of the prefix and the value of its first variable (e.g. "<code>m5</code>" instead of the usual "<code>m-5</code>"). The following variables are passed with the help of this prefix:
{| class="prettytable"
{| class="prettytable"
-
! название || описание
+
! Name || Description
|-
|-
-
| {{ConfigProperty|m_cat_id|int}} || [[K4:Category#CategoryId|ID текущей категории]], т.е. той категории, данные из которой пользователь просматривает в данный момент.
+
| {{ConfigProperty|m_cat_id|int}} || [[K4:Category#CategoryId|Category ID]], i.e. the category that the user is currently viewing.
|-
|-
-
| {{ConfigProperty|m_cat_page|int}} || Номер страницы в списке категорий, находящихся в категории, заданной в переменной [[#m_cat_id|m_cat_id]].
+
| {{ConfigProperty|m_cat_page|int}} || Page number in the categories list in the category indicated in the [[#m_cat_id|m_cat_id]] variable.
|-
|-
-
| {{ConfigProperty|m_lang|int}} || [[K4:Language#LanguageId|ID языка]], на котором нужно показывать содержание сайта (также работает и в административной консоли). Если не задать, то будет использовано [[K4:Language#PrimaryLang|ID основного языка]], заданное в [[K4:Добавление секций в дереве|секции]] "<code>Configuration -> Regional</code>".
+
| {{ConfigProperty|m_lang|int}} || [[K4:Language#LanguageId|Language ID]] in which the site needs to be shown (works the same way in the Administrative Console). If not set, then [[K4:Language#PrimaryLang|Primary Language ID]] will be used, set in the "<code>Configuration -> Regional</code>" [[K4:Добавление секций в дереве|section]].
|-
|-
-
| {{ConfigProperty|m_theme|int}} || [[K4:Theme#ThemeId|ID темы]], которую нужно использовать для показывания пользовательской части сайта. Значение данной переменной не используется в административной консоли. Если не задать, то будет использовано [[K4:Theme#PrimaryTheme|ID основной темы]], заданное в [[K4:Добавление секций в дереве|секции]] "<code>Configuration -> Themes</code>".
+
| {{ConfigProperty|m_theme|int}} || [[K4:Theme#ThemeId|Theme ID]] that needs to be used to show the front-end of the site. The value of this variable isn't used in the Administrative Console. If not set, then [[K4:Theme#PrimaryTheme|ID основной темы]] will be used, which is set in the "<code>Configuration -> Themes</code>" [[K4:Добавление секций в дереве|section]].
|-
|-
| {{ConfigProperty|m_opener|int}}
| {{ConfigProperty|m_opener|int}}
-
| Данная переменная используется для того, чтобы после при нажатии на кнопки "<code>Save</code>" (события [[EventHandler:OnSave|OnSave]], [[EventHandler:OnCreate|OnCreate]], [[EventHandler:OnUpdate|OnUpdate]]) и "<code>Cancel</code>" (события [[EventHandler:OnCancelEdit|OnCancelEdit]], [[EventHandler:OnCancel|OnCancel]]) на панели инструментов на формах редактирования автоматически происходил возврат на тот шаблон, с которого пользователь попал на эту форму редактирования. Для этого используется массив "<code>'''opener_stack_<m_wid>'''</code>", содержащий шаблоны, заходя на которые пользователь в итоге попал на данный шаблон (напр. "<code>Array ('users/user_list', 'users/user_edit_groups');</code>").
+
| This variable is used so that after "<code>Save</code>" is clicked (events [[EventHandler:OnSave|OnSave]], [[EventHandler:OnCreate|OnCreate]], [[EventHandler:OnUpdate|OnUpdate]]) and "<code>Cancel</code>" (event [[EventHandler:OnCancelEdit|OnCancelEdit]], [[EventHandler:OnCancel|OnCancel]]) in the edit form toolbar, so that the user is automatically returned to the template from which he came. For this, the array "<code>'''opener_stack_<m_wid>'''</code>" is used, which contains the templates that the user accessed before finally getting to the given template (for example "<code>Array ('users/user_list', 'users/user_edit_groups');</code>").
-
{{TipBox|Последним элементом в этом массиве будет шаблон, с которого пользователь попал на текущий.}}
+
{{TipBox|The last element in this array will be the template that the user was on before the open template.}}  
-
Данный массив храниться в [[K4:SessionData|сессии]]. Значение, переданное в данной переменной будет рассматриваться как команда к изменению содержания массива "<code>'''opener_stack_<m_wid>'''</code>" для текущего окна:
+
This array is stored in the [[K4:SessionData|session]]. The value, passed in the variable will be taken as a command to change the contents of the "<code>'''opener_stack_<m_wid>'''</code>" array for the open window:
-
* <code>'''r''' (reset)</code> - стереть массив (используется для построения ссылок для [[K4:Добавление секций в дереве|секций]] в дереве);
+
* <code>'''r''' (rest</code> - delete the array (used to build a link for the [[K4:Добавление секций в дереве|section]] tree);
-
* <code>'''d''' (down)</code> - добавить текущий шаблон в массив (используется при переходе на шаблон редактирования записи с шаблона списка записей);
+
* <code>'''d''' (down)</code> - add the open template to the array (used when switching to the editing template from a records list template);
-
* <code>'''u''' (up)</code> - удалить последний шаблон из массива (используется при возвращении с шаблона редактирования записи на шаблон списка записей);
+
* <code>'''u''' (up)</code> - delete the last template from the array (used when returning from the edit template to the grid/records list template);
-
* <code>'''p''' (popup)</code> - добавить текущий шаблон в массив и создать новый [[#m_wid|идентификатор окна]] (тоже самое, что "<code>'''d'''</code>", но только с поправкой на то, что форма редактирования будет открыта в новом всплывающем окне);
+
* <code>'''p''' (popup)</code> - add the open template to the array and create a new [[#m_wid|window ID]] (the same as "<code>'''d'''</code>", except that the edit form will be open in a popup window);
-
* <code>'''s''' (stay)</code> - ничего не делать с массивом (значение по умолчанию).
+
* <code>'''s''' (stay)</code> - do nothing with the array (default value).
|-
|-
-
| {{ConfigProperty|m_wid|int}} || Идентификатор окна, который используется только для всплывающих окон (<code>popups</code>). Для основного окна значение данной переменной равно пустоте. Также идентификатор окна используется в формировании названия массива "<code>'''opener_stack_<m_wid>'''</code>", управляемого через значение переменной [[#m_opener|m_opener]].
+
| {{ConfigProperty|m_wid|int}} || Window ID that's only used for (<code>popups</code>). For main windows, the value is blank. The window ID is also used in formatting the name of the "<code>'''opener_stack_<m_wid>'''</code>" array, which is controlled through the value of the [[#m_opener|m_opener]] variable.
|}
|}
 +
 +
[[en:{{FULLPAGENAME}}]]
 +
[[ru:K4:Переменная окружения]]
 +
 +
[http://guide.in-portal.org/rus/index.php?title=K4:%D0%9F%D0%B5%D1%80%D0%B5%D0%BC%D0%B5%D0%BD%D0%BD%D0%B0%D1%8F_%D0%BE%D0%BA%D1%80%D1%83%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F&oldid=1065  Переменная окружения (revision 1065)]

Current revision

Структура приложения Структура приложения
Статьи в этой категории

The Environment variable is a standard query variable called "env". Name of this variable is defined in ENV_VAR_NAME constant. The purpose of env variable is to pass a large number of variables in a compact way through the website pages. In most cases env variable will carry the values to load the object from the database on the current page (т.е. Prefix и ID), but usage is not limited by that.

Note that in case if in Configuration file of passed the Prefix is allowed auto-loading, then at the time of first call to that object of Prefix and existence of object ID in the env variable then that object will be loaded automatically.

Contents

Structure

The value contained in the environment variable has the following structure:

<session_id>-<template>:m<main_prefix_variables>[:<prefix[.special]>-<value1>[-<value2>...[-<valueN>]]]

For the above scheme, it can be seen that the environment variable is always made up of the following components:

  • session_id - session identifier user;
  • template - path to the template, the rendering of which will be shown on the screen;
  • main_prefix_variables - system variables, among which are theme ID and language ID, which will be used to output information on the page (will be explained later).

Also, it may contain data from an unlimited number of prefixes. Data sets from different prefixes are separated with a colon (":"). The first value in each set is the prefix of the configuration file. If necessary, then the "special" can be indicated in the following format: "prefix.special".

The following is a list of parameters of the prefix that can be passed through the environment variable, delimited using a hyphen ("-"). Parameter names and their order in a single set of a prefix is set in the key QueryString of its Configs|configuration file]]. For example:

'QueryString' => Array(
    1 => 'id',
    2 => 'Page',
    3 => 'event',
    4 => 'mode',
),

The above key value QueryString is the standard for most prefixes and therefore will be described below.

Name Description
id Object ID (Item) that can be used for automatic loading of an object.
Page Page number of the object list (List).
event Event, that needs to be executed from a given prefix.
mode Three types of values are possible:
  • "" - values will be edited in the original table;
  • "t" - values will be edited in a temporary table in the main window;
  • "t<wid>" - values will be edited in a temporary table that was created as the result of a popup, where the window id is "<wid>".
Image:Infobox Icon.gif The values in this array are (case-sensitive).

Getting Data from the Environment Variable

If the URL used to open the site contains an environment variable, then its value will automatically be processed by the system. Direct access to the value of the environment variable isn't recommended. The result of processing each of the passed prefixes creates variables, e.g. "prefix[.special]_VariableName". One variable will be created for each value in the QueryString array of the passed prefix. Variables created by this process can then be used just like any other variables passed in a request to the server (i.e. use the method Application::GetVar). This will be demonstrated in the below example.

'Prefix' => 'sample-prefix',
'QueryString' => Array (
	1 => 'sample_variable',
	2 => 'another_variable',
),
  • Environment Variable Values:
-template:m0--1--s-:sample\-prefix-15-testing

There are two variables defined in the above example for the "sample-prefix" prefix in the configuration file: "sample_variable" and "another_variable". The values that are passed in the environment variable for this prefix are "15" and "testing", respectively. Two variables will be created after processing the environment variable for this prefix:

Name Value
sample-prefix_sample_variable 15
sample-prefix_another_variable testing
Image:Tipbox Icon.gif The variable will be created even if a value isn't passed.

The following code will allow getting the value of either of the variables created above:

PHP Example Template Example
$sample_variable = $this->Application->GetVar('sample-prefix_sample_variable');
value: <inp2:m_Get name="sample-prefix_sample_variable"/>
Image:Infobox Icon.gif To avoid hard-coding the value of the prefix, it can be obtained dynamically using the following methods:kEvent::getPrefixSpecial() (for events) and TagProcessor:getPrefixSpecial() (for tags).

Building Links

Since the environment variable is used to compactly pass data between the pages of a site, the only way to to add something to it is by building a link. All links in K4 are built using the method "Application::HREF". For example, it's used in the method code>Application::Redirect</code> and in the tags m_Link, st_ContentBlock, lang_LanguageLink and m_FormAction. This method accepts the following four parameters.

Parameter Description
$t (string) Name of the template to which a link needs to be built (for example "custom/tests/test_edit"). This parameter is required, but if a blank value is passed, then the current template will be used (the one the user opened).
$prefix (string) This optional parameter is available to make it possible to build a link to the front end of the site while located in the administrative console. To do this, it's value has to be passed as "_FRONT_END_".
Image:Infobox Icon.gif Currently, this functionality doesn't work (see this question) and to build a link to the front-end, "index.php" has to be passed as the value of the index_file parameter.
$params (array) This is a set of parameters that should be passed in a link. In addition to passing general application parameters, it's also possible to pass many special purpose parameters, which are described in below.
$index_file (string) Optional name of the php file that should be used in the resulting link. By default, it's set to "index.php" (for the front-end) and "admin/index.php" (for the administrative console).

Special Purpose Parameters

pass (string) In this parameter are passed the names of the prefix tags (comma delimited) that will be used for building the value of the environment variable in the resulting link. It's also possible to pass the value "all" so that all prefixes in a link are used on the page of a site. For example, "m,sample-prefix" or "all".
Image:Tipbox Icon.gif Always when writing a list of prefixes, the first one must be the prefix "m".
index_file (string) An alternative way to set the value of the "index_file" parameter for the Application::HREF method through the template. For example (if passing "another_index.php"):
http://www.sample-site.com/another_index.php?env=-template:m0--1--s- (with parameter)
http://www.sample-site.com/index.php?env=-template:m0--1--s- (without parameter)
escape (int) If this parameter is defined, then the addslashes function will be applied to the resulting link. When using in a template, use "js_escape" instead of this parameter because it's the latest version of this parameter and will work for all tags. For example (if passing "1"):
http://www.sample-site.com/index.php?env=-template:m0--1--s-:sample\\-prefix-15-testing (with parameter)
http://www.sample-site.com/index.php?env=-template:m0--1--s-:sample\-prefix-15-testing (without parameter)

Usually the "js_escape" (in templates) is used to build links that are used in JavaScript.

anchor (string) This parameter allows adding the value defined in it as an anchor in the resulting link. For example (passing "sample_anchor"):
http://www.sample-site.com/index.php?env=-template:m0--1--s-#sample_anchor (with parameter)
http://www.sample-site.com/index.php?env=-template:m0--1--s- (without parameter)
no_amp (int) If this parameter is passed, then all variables, used in the resulting link will be combined with the "&" symbol (compatible with JavaScript). In all other cases, the variables will be combined using the "&amp;" characters (compatible with HTML). For example, (if passing "1"):
http://www.sample-site.com/index.php?env=-template:m0--1--s-&amp;sample_parameter=value1&amp;another_parameter=value2 (with parameter)
http://www.sample-site.com/index.php?env=-template:m0--1--s-&sample_parameter=value1&another_parameter=value2 (without parameter)

Using Passed Parameters

All passed parameters are divided into 3 groups:

A list of prefixes is taken from the value of the pass parameter and a fragment of the environment variable is set for each prefix that will represent it. If the value of a variable's prefix isn't indicated in the parameter, the value received in the request to the server will be used or, if nothing was passed then a blank space will be used. Al parameters that were used in building the value of the environment variable are removed from the general list of parameters (to avoid them ending up in the resulting link).

The rest of the parameters, having not been used in the environment variable parameter (except special purpose parameters), are added to the resulting link using the line "&amp;" or "&" (if the special purpose parameter is used no_amp).

After the completion of the all of the above steps, the special purpose parameters are applied to the link.

Recording Data

Recording values into the environment variable from templates results in creating the link, which the user will eventually follow. Formatting links from templates is done with the m_Link tag. The below examples demonstrates its use.

Recording Data from a Template

<a href="<inp2:m_Link template='cart' cart_event='OnAddProduct' pass='m,cart,product'/>">Add To Cart</a>

Below are descriptions of m_Link tag parameters, used in the above example.

Parameter Explanation
template (string) Path to the template. On the front-end, this is the path relative to the theme directory.
cart_event (string) The name of the event for the cart prefix. The indicated event will be executed only in the case where the cart prefix is set in the pass parameter.
pass (string) This parameter indicates the prefixes whose data must be passed in the environment variable.

Recording Data from an Event

After successfully executing each event, there is an automatic redirect to the template, from which the event was called. In order for the link that was built for the redirect to contain additional parameters, the method kEvent:setRedirectParam must be used. kEvent:redirect event will allow setting an alternative template to be used in the redirect link. This is demonstrated in the below example.

function OnCreate(&$event)
{
	parent::OnCreate($event);
 
	if ($event->status == erSUCCESS) {
		return ;
	}
 
 
	$event->redirect = 'alternative_destination_template';
	$event->setRedirectParam('pass', 'm,test');
	$event->setRedirectParam('param_name', 'param_value');
}

In this example, the value of the "param_name" variable will be available on the "alternative_destination_template" template. More information on getting the values of passed parameters is written in Above Heading.

System Environment Variables

Apart from data from user prefixes, the "m" (main) prefix is always passed into the environment variable. It contains system environment variables. The prefix's configuration file is located in the "core/units/general" folder and is named "general_config.php" (name of the folder plus "_config.php"). There is a key (PortalStyleEnv) used in this configuration file, because of which the resulting environment variable for the prefix will not contain a dash ("-") between the name of the prefix and the value of its first variable (e.g. "m5" instead of the usual "m-5"). The following variables are passed with the help of this prefix:

Name Description
m_cat_id (int) Category ID, i.e. the category that the user is currently viewing.
m_cat_page (int) Page number in the categories list in the category indicated in the m_cat_id variable.
m_lang (int) Language ID in which the site needs to be shown (works the same way in the Administrative Console). If not set, then Primary Language ID will be used, set in the "Configuration -> Regional" section.
m_theme (int) Theme ID that needs to be used to show the front-end of the site. The value of this variable isn't used in the Administrative Console. If not set, then ID основной темы will be used, which is set in the "Configuration -> Themes" section.
m_opener (int) This variable is used so that after "Save" is clicked (events OnSave, OnCreate, OnUpdate) and "Cancel" (event OnCancelEdit, OnCancel) in the edit form toolbar, so that the user is automatically returned to the template from which he came. For this, the array "opener_stack_<m_wid>" is used, which contains the templates that the user accessed before finally getting to the given template (for example "Array ('users/user_list', 'users/user_edit_groups');").
Image:Tipbox Icon.gif The last element in this array will be the template that the user was on before the open template.

This array is stored in the session. The value, passed in the variable will be taken as a command to change the contents of the "opener_stack_<m_wid>" array for the open window:

  • r (rest - delete the array (used to build a link for the section tree);
  • d (down) - add the open template to the array (used when switching to the editing template from a records list template);
  • u (up) - delete the last template from the array (used when returning from the edit template to the grid/records list template);
  • p (popup) - add the open template to the array and create a new window ID (the same as "d", except that the edit form will be open in a popup window);
  • s (stay) - do nothing with the array (default value).
m_wid (int) Window ID that's only used for (popups). For main windows, the value is blank. The window ID is also used in formatting the name of the "opener_stack_<m_wid>" array, which is controlled through the value of the m_opener variable.

Переменная окружения (revision 1065)