### Starting CBPRuntime and Getting Document Service
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Biznes-protsessy/Klassy/CBPRuntime/StartRuntime.md
This example demonstrates how to get the CBPRuntime instance, start its execution environment, and then retrieve the DocumentService to fetch document fields.
```php
$runtime = CBPRuntime::GetRuntime();
$runtime->StartRuntime();
$documentService = $runtime->GetService("DocumentService");
$arDocumentFields = $documentService->GetDocumentFields($documentType);
foreach ($arDocumentFields as $key => $value)
$arSelectFields[] = $key;
?>
```
--------------------------------
### Getting and Using Runtime Services
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Biznes-protsessy/Klassy/CBPRuntime/GetService.md
Example demonstrating how to get instances of HistoryService and DocumentService from the CBPRuntime and use them to log and update document history.
```php
// Сохраним историю документа $documentId от имени пользователя $userId
$runtime = CBPRuntime::GetRuntime();
$historyService = $runtime->GetService("HistoryService");
$documentService = $runtime->GetService("DocumentService");
$historyIndex = $historyService->AddHistory(
array(
"DOCUMENT_ID" => $documentId,
"NAME" => "New",
"DOCUMENT" => null,
"USER_ID" => $userId,
)
);
$arDocument = $documentService->GetDocumentForHistory($documentId, $historyIndex);
if (is_array($arDocument))
{
$historyService->UpdateHistory(
$historyIndex,
array(
"NAME" => $arDocument["NAME"],
"DOCUMENT" => $arDocument,
)
);
}
?>
```
--------------------------------
### Creating and Starting a Workflow Instance
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Biznes-protsessy/Klassy/CBPRuntime/CreateWorkflow.md
Example of how to use the CBPRuntime::CreateWorkflow method to create and start a new business process instance. Includes basic error handling.
```php
$runtime = CBPRuntime::GetRuntime();
try
{
$wi = $runtime->CreateWorkflow($workflowTemplateId, $documentId, $arParameters);
$wi->Start();
}
catch (Exception $e)
{
//
}
?>
```
--------------------------------
### BX.easing Start and Finish Values Example
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/JS_biblioteka/Animatsija/BX.easing.md
Illustrates how to define the start and finish values for properties that will be animated. This example shows setting initial and final states for 'height' and 'opacity'.
```javascript
start : { height : 0, opacity : 0 },
finish : { height : 100, opacity : 100 }
```
--------------------------------
### Example: Get All Files for a Specific Task
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Zadachi/Klassy/CTaskFiles/GetList.md
This example demonstrates how to retrieve all file IDs associated with a task ID of 2. Ensure the 'tasks' module is included before execution.
```php
// Выбираем все файлы для задачи с ID = 2
if (CModule::IncludeModule("tasks"))
{
$res = CTaskFiles::GetList(
Array("FILES_ID" => "ASC"),
Array("TASK_ID" => "2")
);
while ($arFile = $res->GetNext())
{
echo $arFile["FILE_ID"]."
";
}
}
?>
```
--------------------------------
### Retrieve and Prepare Forum Paths
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Forum/Klassy/CForumNew/GetSites.md
Example demonstrating how to get site-specific forum paths for a given forum ID and then prepare them for a specific message, topic, and forum.
```php
// For forum with code $FID get array of real paths to message
// with code $MID from topic with code $TID
$arForumPaths = CForumNew::GetSites($FID);
$arForumPathsCodes = array_keys($arForumPaths);
for ($i = 0; $i < count($arForumPathsCodes); $i++)
{
$arForumPaths[$arForumPathsCodes[$i]] =
CForumNew::PreparePath2Message($arForumPaths[$arForumPathsCodes[$i]],
array("FORUM_ID"=>$FID,
"TOPIC_ID"=>$TID,
"MESSAGE_ID"=>$MID
)
);
}
```
--------------------------------
### Get Student List Example
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Obuchenie/Klassy/CStudent/GetList.md
Demonstrates how to use CStudent::GetList to retrieve student records by USER_ID and TRANSCRIPT, then iterate through the results to display the RESUME.
```php
if (CModule::IncludeModule("learning"))
{
$USER_ID = 1; $TRANSCRIPT = 46785643;
$res = CStudent::GetList(Array(), Array("USER_ID" => $USER_ID, "TRANSCRIPT" => $TRANSCRIPT));
while ($arProfile = $res->GetNext())
{
echo $arProfile["RESUME"];
}
}
?>
```
--------------------------------
### Example: Registering and Initializing a Custom Extension
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/JS_biblioteka/Registratsija_svoih_rasshirenij.md
This example demonstrates registering a custom extension named 'db_js_demo' with its JavaScript and language files, and then initializing it using CJSCore::Init. It also includes a basic HTML structure and a JavaScript snippet that runs after the DOM is ready.
```php
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
$APPLICATION->SetTitle("Свои расширения");
CJSCore::RegisterExt("db_js_demo", Array(
"js" => "/script_demo.js",
"lang" => "/lang_js.php",
"rel" => array('jquery')
));
CJSCore::Init(array("db_js_demo"));
?>
click Me
```
--------------------------------
### Get IBlock Section List Example
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Informatsionnye_bloki/Funktsii/GetIBlockSectionList.md
This example demonstrates how to use GetIBlockSectionList to fetch and display sections from an information block. It includes necessary Bitrix setup and error handling for module inclusion.
```php
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
$APPLICATION->SetTitle("Каталог");
if(CModule::IncludeModule("iblock"))
{
// если $ID не задан или это не число, тогда
// $ID будет =0, выбираем корневые разделы
$ID = IntVal($_GET['ID']);
// выберем папки из информационного блока $BID и раздела $ID
$items = GetIBlockSectionList($_GET['BID'], $ID, Array("sort"=>"asc"), 10);
while($arItem = $items->GetNext())
{
echo ''.$arItem["NAME"].'
';
echo $arItem["DESCRIPTION"]."
";
}
}
else
ShowError("Модуль не установлен");
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");
?>
```
--------------------------------
### Example Usage of CBlog::PreparePath
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Blogi/Klassy/CBlog/PreparePath.md
This example demonstrates how to use the CBlog::PreparePath method to generate a link to the administrator's blog.
```php
echo 'Блог администратора';
?>
```
--------------------------------
### Get Message List and Paginate
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Tehpodderzhka/Klassy/CTicket/GetMessageList.md
Example of how to use CTicket::GetMessageList to fetch messages for a specific ticket and paginate the results. It demonstrates setting filters and starting pagination.
```php
$mess = CTicket::GetMessageList($a, $b, array("TICKET_ID" => $ID, "TICKET_ID_EXACT_MATCH" => "Y"), $c, $CHECK_RIGHTS);
$mess->NavStart(50);
$messages = $mess->SelectedRowsCount();
?>
```
--------------------------------
### Example description.php File
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Podpiska,_rassylki/Klassy/CPostingTemplate/GetByID.md
This example shows the structure of a typical description.php file used for defining posting template metadata.
```php
$arTemplate =
Array(
"NAME"=>"Дайджест новостей",
"DESCRIPTION"=>"Шаблон генерации дайджеста новостей."
);
?>
```
--------------------------------
### Example of GET HTTP Request URL
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Veb-analitika/Spisok_terminov.md
This is an example of a URL demonstrating the GET HTTP method. Data is encoded directly within the URI, with variables passed as key-value pairs separated by '&', and values URL-encoded.
```http
http://www.bitrixsoft.ru/bitrix/admin/stat_list.php?find_site_id=ru&find_date1_DAYS_TO_BACK=2&find_date2=&lang=ru&set_filter=Y&set_filter=%D3%F1%F2%E0%ED%EE%E2%E8%F2%FC
```
--------------------------------
### Create Course Package Example
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Obuchenie/Klassy/CCoursePackage/CCoursePackage.md
Demonstrates how to create a course package using the CCoursePackage class. Ensure the 'learning' module is included and sufficient permissions are granted. The package will be created in the specified directory. Check for errors during package creation.
```php
if (CModule::IncludeModule("learning"))
{
$COURSE_ID = 97;
if (CCourse::GetPermission($COURSE_ID) >= 'W')
{
@set_time_limit(0);
$package = new CCoursePackage($COURSE_ID);
if (strlen($package->LAST_ERROR) > 0)
{
echo "Error: ".$package->LAST_ERROR;
}
else
{
$success = $package->CreatePackage($PACKAGE_DIR = "/upload/mypackage/");
if (!$success)
echo "Error: ".$package->LAST_ERROR;
else
echo "Ok!";
}
}
}
?>
```
--------------------------------
### Example Usage: Get User Subscription and Newsletter Categories
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Podpiska,_rassylki/Klassy/CSubscriptionGeneral/GetUserSubscription.md
This example demonstrates how to get the current user's subscription from cookies and then retrieve their newsletter categories. Further steps to show a subscription form are commented out.
```php
//get current user subscription from cookies
$aSubscr = CSubscription::GetUserSubscription();
//get user's newsletter categories
$aSubscrRub = CSubscription::GetRubricArray(intval($aSubscr["ID"]));
//show subscription form
//.....
```
--------------------------------
### Example Usage of CCoursePackage::CreateManifest()
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Obuchenie/Klassy/CCoursePackage/CreateManifest.md
This example demonstrates how to use the CCoursePackage::CreateManifest() method. It includes checking module inclusion, course permissions, creating a CCoursePackage object, and outputting the generated manifest.
```php
if (CModule::IncludeModule("learning"))
{
$COURSE_ID = 97;
if (CCourse::GetPermission($COURSE_ID) >= 'W')
{
@set_time_limit(0);
$package = new CCoursePackage($COURSE_ID);
if (strlen($package->LAST_ERROR) > 0)
{
echo "Error: ".$package->LAST_ERROR;
}
else
{
echo htmlspecialchars($package->CreateManifest());
}
}
}
?>
```
--------------------------------
### Get Web Form Permission
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Veb-formy/Klassy/CForm/GetPermission.md
Example of how to get the current user's permission level for a specific web form and display a message based on it.
```php
$FORM_ID = 4;
// получим права текущего пользователя
$permission = CForm::GetPermission($FORM_ID);
if ($permission==10) echo "У вас есть право на заполнение веб-формы";
?>
```
--------------------------------
### Full Page Example for Image Viewer
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/JS_biblioteka/Publichnyj_dialog_pokaza_fajlov.md
A complete PHP page example demonstrating how to initialize the viewer and display multiple images using specific data attributes on img tags.
```php
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
$APPLICATION->SetTitle("Просмотр изображений");
CJSCore::Init(Array("viewer"));
?>
```
--------------------------------
### StartRuntime Method
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Biznes-protsessy/Klassy/CBPRuntime/StartRuntime.md
Initializes the execution environment. The execution environment must be started before any use. Some methods automatically start the environment, and restarting it is safe.
```APIDOC
## CBPRuntime::StartRuntime
### Description
Initializes the execution environment for Bitrix business processes. It is safe to call this method multiple times.
### Method
`public int StartRuntime( void );`
### Parameters
This method does not accept any parameters.
### Return Value
Returns an integer status code (details not specified in source).
### Examples
```php
$runtime = CBPRuntime::GetRuntime();
$runtime->StartRuntime();
$documentService = $runtime->GetService("DocumentService");
$arDocumentFields = $documentService->GetDocumentFields($documentType);
foreach ($arDocumentFields as $key => $value)
$arSelectFields[] = $key;
?>
```
```
--------------------------------
### Example Usage of GetFilterPresetConditionById
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Zadachi/Klassy/CTaskFilterCtrl/GetFilterPresetConditionById.md
This example demonstrates how to get a filter condition by its preset ID and use it with CTasks::GetList. Ensure the 'tasks' module is included.
```php
getId();
$bGroupMode = false;
$oFilter = CTaskFilterCtrl::getInstance($userId, $bGroupMode);
$selectedFilter = $oFilter->getSelectedFilterPresetId();
$arFilter = $oFilter->getFilterPresetConditionById($selectedFilter);
// Покажем условия фильтра
var_dump($arFilter);
// Это условие можно использовать в CTasks::GetList();
$rsTasks = CTasks::GetList(array(), $arFilter);
?>
```
```php
Выведет:
array(1) {
["::SUBFILTER-ROOT"]=>
array(3) {
["::LOGIC"]=>
string(3) "AND"
["MEMBER"]=>
int(1)
["STATUS"]=>
array(6) {
[0]=>
int(-2)
[1]=>
int(-1)
[2]=>
int(1)
[3]=>
int(2)
[4]=>
int(3)
[5]=>
int(7)
}
}
}
```
--------------------------------
### Get Answer by ID Example
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Obuchenie/Klassy/CLAnswer/GetByID.md
This example demonstrates how to use CLAnswer::GetByID to fetch and display the content of an answer. Ensure the 'learning' module is included.
```php
if (CModule::IncludeModule("learning"))
{
$ANSWER_ID = 573;
$res = CLAnswer::GetByID($ANSWER_ID);
if ($arAnswer = $res->GetNext())
{
echo "Name: ".$arAnswer["ANSWER"];
}
}
?>
```
--------------------------------
### Example 1: Get all catalog information blocks
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Informatsionnye_bloki/Funktsii/GetIBlockList.md
This example demonstrates how to fetch all information blocks of type 'catalog' and iterate through them using the `GetNext()` method.
```APIDOC
## Example 1: Get all catalog information blocks
### Description
Fetches all information blocks of type 'catalog' and displays their names.
### Code
```php
if(CModule::IncludeModule("iblock"))
{
// Get all information blocks of type "catalog"
$iblocks = GetIBlockList("catalog");
// Loop through all blocks
while($arIBlock = $iblocks->GetNext())
{
// The GetNext() method automatically applies htmlspecialchars to field values.
echo "Name: " . $arIBlock["NAME"] . "
";
}
}
?>
```
```
--------------------------------
### Example of Adding a New Blog User
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Blogi/Klassy/CBlogUser/Add.md
This example demonstrates how to create a new blog user profile for the current user using the CBlogUser::Add method. It includes error handling to display any exceptions.
```php
//создадим профайл пользователя блога для текущего пользователя
$arFields = array(
"USER_ID" => $USER->GetID(),
"=LAST_VISIT" => $DB->GetNowFunction(),
"=DATE_REG" => $DB->GetNowFunction(),
"ALLOW_POST" => "Y",
"ALIAS" => "Псевдоним пользователя",
"DESCRIPTION" => "Обычный пользователь сайта с блогом",
"INTERESTS" => "программирование, PHP, MySQL, Bitrix, Битрикс"
);
$newID = CBlogUser::Add($arFields);
if(IntVal($newID)>0)
{
echo "Новый пользователь блога [".$newID."] добавлен.";
}
else
{
if ($ex = $APPLICATION->GetException())
echo $ex->GetString();
}
?>
```
--------------------------------
### Step-by-Step Re-indexing Example
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Poisk/Klassy/CSearch/ReIndexAll.md
Demonstrates how to perform a step-by-step re-indexing using CSearch::ReIndexAll. The state (NS) should be persisted between calls, for example, by saving it to a file.
```php
//Этот пример не является примером пошаговой индексации.
//Для этого надо вызывать метод ReIndexAll только один раз за запуск скрипта.
//А промежуточное состояние (NS) можно сохранять например в файле.
$NS = false;
$NS = CSearch::ReIndexAll(false, 60, $NS);
while(is_array($NS))
$NS = CSearch::ReIndexAll(false, 60, $NS);
echo $NS;
?>
```
--------------------------------
### Navigation Start Parameters Example
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Internet-magazin/Klassy/CSalePersonType/GetList.md
Provides an example of the arNavStartParams array, which is used for pagination and limiting the number of records returned. It can include 'nTopCount' for limiting results.
```php
array(
"nTopCount" => "количество",
// ... другие параметры навигации
)
```
--------------------------------
### Example: Tracking File Downloads for a Guest
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Veb-analitika/Klassy/CStatEvent/GetListByGuest.md
Demonstrates how to check if a guest has already downloaded a specific file within the last hour and records the event if not. It involves checking event types and then querying existing events for the guest.
```php
// зафиксируем событие типа
// "Скачивание файла manual.chm" (download/manual)
// если такого типа не существует, он будет автоматически создан
// событие будет фиксироваться по параметрам
// текущего посетителя сайта
// сначала проверим - не скачивал ли уже текущий посетитель
// этот файл в течение последнего часа
// получим ID типа события
$rs = CStatEventType::GetByEvents($event1, $event2);
if ($ar = $rs->Fetch())
{
// теперь получим все события данного типа
// для текущего посетителя сайта,
// произошедшие за последний час (3600 секунд)
$rs = CStatEvent::GetListByGuest(
$_SESSION["SESS_GUEST_ID"],
$ar["TYPE_ID"], "", 3600
);
// если таких событий не было...
if (!($ar=$rs->Fetch()))
{
// ...добавляем данное событие
CStatEvent::AddCurrent("download", "manual");
}
}
?>
```
--------------------------------
### Formatting Price Example
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/JS_biblioteka/Valjuty.md
Demonstrates how to use BX.Currency.currencyFormat to display a price, with an example showing how to include the currency symbol and how to display just the numeric value.
```APIDOC
## Formatting Price Example
### Description
Demonstrates how to use BX.Currency.currencyFormat to display a price, with an example showing how to include the currency symbol and how to display just the numeric value.
### Code
```javascript
/*
Result:
item will contain the string "$141.56"
item2 will contain the string "141.56"
*/
```
```
--------------------------------
### Get User Permissions for Blog Posts
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Blogi/Klassy/CBlogUser/GetUserPerms.md
Example of how to get the current user's permission level for posts in a specific blog. Ensure the $userID variable is defined before use.
```php
// получим уровень доступа к сообщениям блога с идентификатором 2
$blogID = 2;
$arUserGroups = CBlogUser::GetUserGroups($userID, $blogID, "Y", BLOG_BY_USER_ID);
$perms = CBlogUser::GetUserPerms(arUserGroups, $blogID, 0, BLOG_PERMS_POST);
echo "Вы имеете следующее право на сообщения блога: ".$perms;
?>
```
--------------------------------
### Get Blog Image Information by ID
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Blogi/Klassy/CBlogImage/GetByID.md
Use this example to retrieve and display information for a blog image using its ID. Ensure the ID exists to get a valid result.
```php
$res = CBlogImage::GetByID(16);
if($res)
print_r($res);
```
--------------------------------
### Get Blog User Groups Example
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Blogi/Klassy/CBlogUser/GetUserGroups.md
Example of how to use CBlogUser::GetUserGroups to retrieve the blog groups for the current user in a specific blog. It checks if the result is an array before printing.
```php
// получим группы пользователей блога с ID=1, к которым привязан текущий пользователь
$ID = $USER->GetID();
$arUserGroups = CBlogUser::GetUserGroups($ID, 1, "", BLOG_BY_USER_ID);
if(is_array($arUserGroups))
print_r($arUserGroups);
?>
```
--------------------------------
### Using CBPRuntime to Access Services
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Biznes-protsessy/Klassy/CBPRuntime/GetRuntime.md
Obtain the runtime instance, start it, and then retrieve services like DocumentService to interact with document fields. Ensure the runtime is started before accessing services.
```php
$runtime = CBPRuntime::GetRuntime();
$runtime->StartRuntime();
$documentService = $runtime->GetService("DocumentService");
$arDocumentFields = $documentService->GetDocumentFields($documentType);
foreach ($arDocumentFields as $key => $value)
{
print_r($value);
}
?>Копировать
```
--------------------------------
### Example Usage of CCurrency::GetList
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Valjuty/Klassy/CCurrency/GetList.md
This example demonstrates how to fetch a list of currencies sorted by name and display them along with formatted currency values.
```php
// Выведем список валют на текущем языке, отсортированный по названию
// Кроме того выведем сумму 11.95 в формате этой валюты на текущем языке
$lcur = CCurrency::GetList(($by="name"), ($order="asc"), LANGUAGE_ID);
while($lcur_res = $lcur->Fetch())
{
echo "[".$lcur_res["CURRENCY"]."] ".$lcur_res["FULL_NAME"].": ";
echo CurrencyFormat(11.95, $lcur_res["CURRENCY"])."
";
}
?>
```
--------------------------------
### Get User Post Permissions
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Blogi/Klassy/CBlogPost/GetBlogUserPostPerms.md
Example of how to get the current user's permission level for a specific blog post using GetBlogUserPostPerms. Ensure the USER object is available in the scope.
```php
$perms = CBlogPost::GetBlogUserPostPerms(1, $USER->GetID());
echo "Вы имеете следующее право на сообщение: ".$perms;
?>
```
--------------------------------
### Example OnBeforeEventAdd Handler in Bitrix
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Glavnyj_modul'/Sobytija/OnBeforeEventAdd.md
Demonstrates how to register and implement an event handler for OnBeforeEventAdd. This example adds a new macro, modifies an existing one, and changes the site ID.
```php
//Handler in the /bitrix/php_interface/init.php file
AddEventHandler("main", "OnBeforeEventAdd", array("MyClass", "OnBeforeEventAddHandler"));
class MyClass
{
public static function OnBeforeEventAddHandler(&$event, &$lid, &$arFields)
{
$arFields["NEW_FIELD"] = "New macro for the mail template";
$arFields["VS_BIRTHDAY"] = "Change existing macro";
$lid = 's2'; //Change site binding
}
}
?>
```
--------------------------------
### Example: Filter and Get Referrers from Google Domains
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Veb-analitika/Klassy/CReferer/GetList.md
This example demonstrates how to filter referrer entries to include only those from 'google' domains and group them by referring domain. It then iterates through the results and prints each entry.
```php
// отфильтруем только заходы с доменов "google"
// сгруппировав по ссылающемуся домену
$arFilter = array(
"FROM_DOMAIN" => "google",
"GROUP" => "S"
);
// получим список записей
$rs = CReferer::GetList(
($by = "s_url_from"),
($order = "desc"),
$arFilter,
$is_filtered,
$total,
$group_by,
$max
);
// выведем все записи
while ($ar = $rs->Fetch())
{
echo ""; print_r($ar); echo "
";
}
?>
```
--------------------------------
### GetList Example: Fetching Active Tests for a Course
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Obuchenie/Klassy/CTest/GetList.md
This example demonstrates how to retrieve all active tests for a specific course, sorted by their sort index. Ensure the 'learning' module is included.
```php
if (CModule::IncludeModule("learning"))
{
$COURSE_ID = 97;
$res = CTest::GetList(
Array("SORT"=>"ASC"),
Array("ACTIVE" => "Y", "COURSE_ID" => $COURSE_ID)
);
while ($arTest = $res->GetNext())
{
echo "Test name: ".$arTest["NAME"]."
";
}
}
?>
```
--------------------------------
### Example: Get Dynamic List with Filter
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Veb-analitika/Klassy/CPage/GetDynamicList.md
This example demonstrates how to use CPage::GetDynamicList to retrieve visit data for a specific URL within a date range and filtered by advertising campaign.
```php
$url = "http://www.bitrixsoft.ru/about/index.php";
// установим фильтр на декабрь 2007 года
// по прямым заходам с рекламной кампании 1 либо 2
$arFilter = array(
"DATE1" => "01.12.2007",
"DATE2" => "31.12.2007",
"ADV" => "1 | 2",
"ADV_DATA_TYPE" => "P"
);
// получим набор записей
$rs = CPage::GetDynamicList(
$url,
($by="s_date"),
($order="desc"),
$arFilter,
);
// выведем все записи
while ($ar = $rs->Fetch())
{
echo ""; print_r($ar); echo "
";
}
?>
```
--------------------------------
### Example Usage of CreatePackage
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Obuchenie/Klassy/CCoursePackage/CreatePackage.md
Example of how to use the CCoursePackage::CreatePackage method to create a course package archive.
```APIDOC
### Example Usage
```php
if (CModule::IncludeModule("learning"))
{
$COURSE_ID = 97;
if (CCourse::GetPermission($COURSE_ID) >= 'W')
{
@set_time_limit(0);
$package = new CCoursePackage($COURSE_ID);
if (strlen($package->LAST_ERROR) > 0)
{
echo "Error: " . $package->LAST_ERROR;
}
else
{
$success = $package->CreatePackage($PACKAGE_DIR = "/upload/mypackage/");
if (!$success)
echo "Error: " . $package->LAST_ERROR;
else
echo "Ok!";
}
}
}
?>
```
```
--------------------------------
### Get Element by ID in PHP
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Informatsionnye_bloki/Klassy/CIBlockElement/GetByID.md
Fetches an information block element by its ID and displays its name. Ensure the 'iblock' module is included before use. This example retrieves the element ID from a GET parameter.
```php
if(!CModule::IncludeModule("iblock"))
return;
$res = CIBlockElement::GetByID($_GET["PID"]);
if($ar_res = $res->GetNext())
echo $ar_res['NAME'];
?>
```
--------------------------------
### Get Root Activity and Document ID
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Biznes-protsessy/Klassy/CBPActivity/GetRootActivity.md
Example of how to retrieve the root activity object and then get the document ID associated with it. This is commonly used within a business process to interact with the document it is processing.
```php
$rootActivity = $this->GetRootActivity();
$documentId = $rootActivity->GetDocumentId();
?>
```
--------------------------------
### Example Handler Function
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Poisk/Sobytija/OnSearchGetFileContent.md
An example of how to register and implement a handler for the OnSearchGetFileContent event to index compressed gzip files.
```APIDOC
## Example Handler Function
This example demonstrates how to register an event handler for `OnSearchGetFileContent` to index compressed gzip files.
### Code
```php
//init.php
// Indexing compressed gzip files.
// Registering the event handler for the "OnSearchGetFileContent" event of the "search" module
AddEventHandler("search", "OnSearchGetFileContent", array("CMyClass", "OnSearchGetFileContent_gzip"));
class CMyClass
{
public static function OnSearchGetFileContent_gzip($absolute_path)
{
if(file_exists($absolute_path) && is_file($absolute_path) && substr($absolute_path, -3) == ".gz")
{
return array(
"TITLE" => basename($absolute_path),
"CONTENT" => implode("\n", gzfile($absolute_path)) ,
"PROPERTIES" => array(),
);
}
else
return false;
}
}
?>
```
```
--------------------------------
### Add New Chapter Example
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Obuchenie/Klassy/CChapter/Add.md
Demonstrates how to add a new chapter to the learning module. Ensure the 'learning' module is included and required fields are populated. Check for exceptions on failure.
```php
if (CModule::IncludeModule("learning"))
{
$COURSE_ID = 97;
$arFields = Array(
"COURSE_ID" => $COURSE_ID,
"ACTIVE" => "Y",
"NAME" => "Chapter 1",
"SORT" => "100",
"DETAIL_TEXT" => "In this chapter ...",
);
$chapter = new CChapter;
$ID = $chapter->Add($arFields);
$success = ($ID>0);
if($success)
{
echo "Ok!";
}
else
{
if($e = $APPLICATION->GetException())
echo "Error: ".$e->GetString();
}
}
?>
```
--------------------------------
### Get Multi-Select Value for Editing Result
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Veb-formy/Klassy/CForm/GetMultiSelectValue.md
This example demonstrates how to use CForm::GetMultiSelectValue when editing an existing result. It first retrieves form data and then uses it to get the selected values for a multi-select question.
```php
/*******************************************
Редактирование результата
*******************************************/
$RESULT_ID = 12; // ID результата
// если была нажата кнопка "Сохранить" то
if (strlen($_REQUEST["save"])>0)
{
// используем данные пришедшие с формы
$arrVALUES = $_REQUEST;
}
else
{
// сформируем этот массив из данных по результату
$arrVALUES = CFormResult::GetDataByIDForHTML($RESULT_ID);
}
?>
```
--------------------------------
### Example Usage of CTaskLog::GetChanges
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Zadachi/Klassy/CTaskLog/GetChanges.md
This example demonstrates how to use the CTaskLog::GetChanges method. It first retrieves a task by its ID, then defines new field values, and finally calls GetChanges to get the differences.
```php
if (CModule::IncludeModule("tasks"))
{
$rsTask = CTasks::GetByID(2);
if ($arTask = $rsTask->Fetch())
{
$arFields = array(
"TITLE" => "New task title",
"RESPONSIBLE_ID" => 45
);
$arChanges = CTaskLog::GetChanges($arTask, $arFields);
}
}
?>
```
--------------------------------
### Example Usage of CBlogTrackback::GetPing
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Blogi/Klassy/CBlogTrackback/GetPing.md
This example demonstrates how to use the CBlogTrackback::GetPing method. It includes checks for the blog module, request method, and extracts parameters from the request to send a Trackback.
```php
if (CModule::IncludeModule("blog"))
{
$postID = IntVal($postID);
$blogUrl = Trim($blogUrl);
if (strtoupper($_SERVER["REQUEST_METHOD"]) != "POST")
{
LocalRedirect(CBlogPost::PreparePath($blogUrl, $postID));
die();
}
$arParams = array();
if (isset($_REQUEST))
{
if (isset($_REQUEST["title"]))
$arParams["title"] = $_REQUEST["title"];
if (isset($_REQUEST["url"]))
$arParams["url"] = $_REQUEST["url"];
if (isset($_REQUEST["excerpt"]))
$arParams["excerpt"] = $_REQUEST["excerpt"];
if (isset($_REQUEST["blog_name"]))
$arParams["blog_name"] = $_REQUEST["blog_name"];
}
CBlogTrackback::GetPing($blogUrl, $postID, $arParams);
}
?>
```
--------------------------------
### Usage Example
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Blogi/Klassy/blogTextParser/convert.md
Demonstrates how to use the `convert` method to format blog post detail text, including handling images.
```APIDOC
### Usage Example
```php
$arPost = CBlogPost::GetByID(3);
$p = new blogTextParser();
$res = CBlogImage::GetList(
array("ID"=>"ASC"),
array(
"POST_ID"=>$arPost['ID'],
"BLOG_ID"=>$arPost['BLOG_ID']
)
);
while ($arImage = $res->Fetch())
$arImages[$arImage['ID']] = $arImage['FILE_ID'];
$text = $p->convert($arPost["DETAIL_TEXT"], false, $arImages);
?>
```
```
--------------------------------
### Get Document States in PHP
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Biznes-protsessy/Klassy/CBPDocument/GetDocumentStates.md
Fetches all workflow states for a specific document and iterates through them to get user tasks. This example demonstrates how to use the GetDocumentStates method with a document type and ID, and then process the returned states.
```php
$documentType = array("bizproc", "CBPVirtualDocument", "type_" . $blockId);
$documentId = array("bizproc", "CBPVirtualDocument", $id);
$arDocumentStates = CBPDocument::GetDocumentStates($documentType, $documentId);
foreach ($arDocumentStates as $arDocumentState)
{
$arDocumentStateTasks = CBPDocument::GetUserTasksForWorkflow($GLOBALS["USER"]->GetID(), $arDocumentState["ID"]);
print_r($arDocumentStateTasks);
}
?>
```
--------------------------------
### Creating and Displaying a Popup Window
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/JS_biblioteka/Publichnaja_okonnaja_biblioteka.md
This snippet demonstrates how to initialize and display a popup window using the BX.PopupWindow class. It includes setting popup properties, content, and event handling for showing the popup on a click event. Ensure the 'popup' CJSCore module is initialized.
```php
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
$APPLICATION->SetTitle("PopUp");
CJSCore::Init(array("popup"));
?>
```
--------------------------------
### Get Execution Result of Business Process
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Biznes-protsessy/Klassy/CBPWorkflow/GetExecutionResult.md
Retrieves the execution result of a business process and displays its status. This example demonstrates how to fetch the workflow runtime, get a specific workflow instance, and then use GetExecutionResult to determine its state.
```php
$runtime = CBPWorkflow::GetRuntime();
try
{
$workflow = $runtime->GetWorkflow($workflowId);
}
catch (Exception $e)
{
//
}
$executionResult = $workflow->GetExecutionResult();
switch ($executionResult)
{
case CBPActivityExecutionResult::None:
echo "Нет";
break;
case CBPActivityExecutionResult::Succeeded:
echo "Успешно";
break;
case CBPActivityExecutionResult::Canceled:
echo "Отменено";
break;
case CBPActivityExecutionResult::Faulted:
echo "Ошибка";
break;
case CBPActivityExecutionResult::Uninitialized:
echo "Не инициализировано";
break;
default:
echo "Не определено";
}
?>
```
--------------------------------
### Registering and Implementing a Basic Handler
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Informatsionnye_bloki/Sobytija/OnBeforeIBlockElementAdd.md
Example of registering an event handler in init.php and implementing a handler that checks for and requires a symbolic code for the element.
```php
// file /bitrix/php_interface/init.php
// register handler
AddEventHandler("iblock", "OnBeforeIBlockElementAdd", Array("MyClass", "OnBeforeIBlockElementAddHandler"));
class MyClass
{
// create event handler "OnBeforeIBlockElementAdd"
public static function OnBeforeIBlockElementAddHandler(&$arFields)
{
if(strlen($arFields["CODE"])<=0)
{
global $APPLICATION;
$APPLICATION->throwException("Enter the symbolic code.");
return false;
}
}
}
?>
```
--------------------------------
### Example 2: Get news blocks with specific filters and sorting
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Informatsionnye_bloki/Funktsii/GetIBlockList.md
This example shows how to retrieve a limited number of news information blocks, excluding a specific symbolic code, sorted by name, and then iterates through them to display links.
```APIDOC
## Example 2: Get news blocks with specific filters and sorting
### Description
Retrieves up to 5 news information blocks, excluding those with the symbolic code 'company_news', sorted by name in ascending order. It then displays links to the list page for each block and demonstrates fetching elements within each block.
### Code
```php
if(CModule::IncludeModule("iblock"))
{
// Get 5 news information blocks, excluding "company_news", sorted by name
$iblocks = GetIBlockList(
"news",
Array(),
"company_news",
Array("name"=>"asc"),
5
);
// Loop through the information blocks
while($arIBlock = $iblocks->GetNext()):
?>
// Display a link to the list page for the news block
">
// Fetch the 5 most recent elements for each information block
$items = GetIBlockElementList(
$arIBlock["ID"],
false,
Array("ACTIVE_FROM"=>"desc", "sort"=>"asc"),
5
);
// Loop through the elements (news items)
while($arItem = $items->GetNext())
{
// Further processing of news items would go here
}
endwhile;
}
?>
```
```
--------------------------------
### Get User Account by ID
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Internet-magazin/Klassy/CSaleUserAccount.md
Retrieves the parameters of a user account by its ID. This method is available starting from version 4.0.6.
```APIDOC
## Get User Account by ID
### Description
Returns an associative array of account parameters for the account with the specified ID.
### Method
`CSaleUserAccount::GetByID(int $ID)
`
### Parameters
#### Path Parameters
- **ID** (int) - Required - The ID of the account.
### Version
Available since 4.0.6
```
--------------------------------
### Example Usage of CPostingTemplate::GetList()
Source: https://github.com/mosolovi/bitrix_full_docs/blob/main/bitrix_docs/Podpiska,_rassylki/Klassy/CPostingTemplate/GetList.md
Demonstrates how to retrieve and iterate through the list of available subscription template directories using CPostingTemplate::GetList().
```php
//get template directories
$arTemplates = CPostingTemplate::GetList();
foreach($arTemplates as $template_dir):
?>
endforeach;
?>
```